繁体   English   中英

Javascript / JQuery中的动态数组

[英]Dynamic arrays in Javascript/JQuery

为什么即使var email等于字符串,我的数组长度也总是为0。 (我已经通知了var电子邮件,并且数据在那里)。

    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);
        }
    });

因为您要向数组添加属性。

var a = [];
a.foo = 42;
a.length === 0; // true

而是试试

emails.push(email);

这与emails[emails.length] = email

作为旁白:

var emails = new Array();

不好。 您应该使用[]而不是new Array()主要是因为它更简洁易读。

if (email != '') {

上面的内容可以替换为if (email) {以防jQuery返回undefinednull

为了使整个代码更加优雅,你应该使用

var emails = $('.emailBox input').map(function() {
    return this.value;
}).filter(function (k, v) { return v; }).get();

还是没有jQuery

var emails = [].map.call(document.querySelectorAll(".emailBox input"), function (v) {
    return v.value;
}).filter(function (v) { return v; });

虽然您需要QSA垫片和ES5垫片来支持传统平台。

编辑:

如果要使数组唯一,则减少它。

var arr = arr.reduce(function (memo, val, key, arr) {
  // if the first index of the value is the index then add it.
  // if the first index is different then we already have it.
  if (arr.indexOf(val) === key) {
    memo.push(val);
  }
  return memo;
}, []);

您可以使用一些jQuery方法完成所有这些操作。

var emails = $('.emailBox input')
              .map(function() { return $(this).val() || null; })
              .get();

jsFiddle

电子邮件[email] =电子邮件没有按照您的意愿执行。 尝试

emails.push(email);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM