Javascript/JQuery 中的动态数组
为什么我的数组长度总是为 0,即使 var email 等于字符串。 (我已经发出了 var email 的警报并且数据就在那里)。
var emails = new Array();
//get all the emails
$('.emailBox input').each(function (i)
{
var email = $(this).val();
if(email != '')
{
emails[email] = email;
alert(emails.length);
}
});
Why does my array length always come out to 0 even though var email is equal to a string. (I've alerted out var email and the data is there).
var emails = new Array();
//get all the emails
$('.emailBox input').each(function (i)
{
var email = $(this).val();
if(email != '')
{
emails[email] = email;
alert(emails.length);
}
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
因为您要向数组添加一个属性。
相反,请尝试
emails.push(email);
这与
emails[emails.length] = email
相同顺便说一句:
var emails = new Array() ;
很糟糕。您应该使用
[]
而不是new Array()
主要是因为它更加简洁和可读。if (email != '') {
上面的内容可以用
if (email) {
替换,以防 jQuery 返回undefined
或null
为了使整个代码更优雅,您应该使用
或不使用 jQuery,
尽管您需要 QSA 填充程序和 ES5 填充程序来支持旧平台。
编辑:
如果您希望数组是唯一的,则减少它。
Because you're adding a property to the array.
Instead try
emails.push(email);
This is the same as
emails[emails.length] = email
As an aside:
var emails = new Array();
Is bad. You should be using
[]
instead ofnew Array()
mainly because it's more terse and readable.if (email != '') {
The above can be replace with
if (email) {
in case jQuery ever returnsundefined
ornull
To make the entire code more elegant you should use
Or without jQuery
Although you'll need a QSA shim and a ES5 shim for legacy platform support.
Edit:
If you want the array to be unique then reduce it.
您可以使用一些 jQuery 方法来完成所有这些工作。
jsFiddle。
You could do all of that using a few jQuery methods.
jsFiddle.
emails[email] = 电子邮件没有执行您希望它执行的操作。尝试
emails[email] = email isn't doing what you want it to do. Try