简体   繁体   中英

Dynamic arrays in Javascript/JQuery

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

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

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.

if (email != '') {

The above can be replace with if (email) { in case jQuery ever returns undefined or null

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

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.

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.

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

jsFiddle .

emails[email] = email isn't doing what you want it to do. Try

emails.push(email);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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