【问题标题】:Array.length seemingly not working; console.log shows otherwiseArray.length 似乎不起作用; console.log 以其他方式显示
【发布时间】:2015-04-10 00:43:23
【问题描述】:

我想最终将contactList写入页面,但即使console.log显示contactList正在正确接收从localStorage推送的联系人,它的长度仍为1!当我尝试迭代 contactList 以写入页面时,它没有按预期工作,我看到未定义的值应该在哪里。

var contactList = [];
window.onload = init;
function init(){
    var data = window.localStorage.getItem("contacts");
    if(data){
        myData = JSON.parse(data);
        console.log("This is local storage:\n");
        console.log(myData);
        console.log("This is contact list before I push local storage:\n");
        console.log(contactList);
        contactList.push(myData);
        console.log("This is contact list after I push local storage:\n");   
        console.log(contactList);
        var j = contactList.length;
        console.log("This is the length of contact list:\n");
        console.log(contactList.length);
    
    }
}

这是我的控制台窗口的示例:

这是本地存储:

form.js(第 12 行) [[[对象 { firstname="hi", lastname="hi", number="hi"}], 对象 { firstname="hi", lastname="hi", number="hi"}], Object{ firstname="hi", lastname="hi", number="hi"}] form.js(第 13 行)

这是我推送本地存储之前的联系人列表:

form.js(第 14 行) [] form.js(第 15 行)

这是我推送本地存储后的联系人列表:

form.js(第 17 行) [[[[对象 { firstname="hi", lastname="hi", number="hi"}], Object { firstname="hi", lastname="hi", number="hi"}], Object { firstname="hi", > lastname="hi", number="hi"}]] form.js(第 18 行)

这是联系人列表的长度:

form.js(第 20 行) 1

【问题讨论】:

  • 记录数据和 myData 显示什么?
  • 您将整个数组推入第一个索引。推送不会单独添加所有元素
  • epascarello 你是对的,谢谢。我使用 concat 修复了它。
  • 或者您可以将其设置为contactList启动,无需调用该代码onload。

标签: javascript


【解决方案1】:

这是push 的预期结果。看起来你想使用concat

push 会将任何参数附加到数组末尾的新元素中。如果您添加一个字符串,它将添加该字符串。如果您添加一个数组,它将添加一个数组...作为最后一个元素。它不会使结果数组变平。另一方面,concat 将连接两个数组并返回一个新数组。但原始数组将保持不变。

【讨论】:

    【解决方案2】:
    var a = [1]
    
    console.log(a.length) // 0
    
    var b = [2]
    
    var c = a.push(b)
    
    console.log(c) // [1, [2]] 
    
    console.log(c.length) // 2
    

    尝试使用 concat():

    var a = [1]
    
    console.log(a.length) // 1
    
    var b = [2]
    
    var c = a.concat(b)
    
    console.log(c) // [1, 2] <<< Desired behaviour
    
    console.log(c.length) // 2
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-24
      • 2023-03-25
      • 1970-01-01
      • 2012-08-25
      • 1970-01-01
      • 2023-02-04
      • 1970-01-01
      • 2015-10-10
      相关资源
      最近更新 更多