簡體   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