【发布时间】: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