简体   繁体   English

Javascript / JQuery中的动态数组

[英]Dynamic arrays in Javascript/JQuery

Why does my array length always come out to 0 even though var email is equal to a string. 为什么即使var email等于字符串,我的数组长度也总是为0。 (I've alerted out var email and the data is there). (我已经通知了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);
        }
    });

Because you're adding a property to the array. 因为您要向数组添加属性。

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

Instead try 而是试试

emails.push(email);

This is the same as emails[emails.length] = email 这与emails[emails.length] = email

As an aside: 作为旁白:

var emails = new Array();

Is bad. 不好。 You should be using [] instead of new Array() mainly because it's more terse and readable. 您应该使用[]而不是new Array()主要是因为它更简洁易读。

if (email != '') {

The above can be replace with if (email) { in case jQuery ever returns undefined or null 上面的内容可以替换为if (email) {以防jQuery返回undefinednull

To make the entire code more elegant you should use 为了使整个代码更加优雅,你应该使用

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

Or without jQuery 还是没有jQuery

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

Although you'll need a QSA shim and a ES5 shim for legacy platform support. 虽然您需要QSA垫片和ES5垫片来支持传统平台。

Edit: 编辑:

If you want the array to be unique then reduce it. 如果要使数组唯一,则减少它。

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;
}, []);

You could do all of that using a few jQuery methods. 您可以使用一些jQuery方法完成所有这些操作。

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

jsFiddle . jsFiddle

emails[email] = email isn't doing what you want it to do. 电子邮件[email] =电子邮件没有按照您的意愿执行。 Try 尝试

emails.push(email);

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

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