[英]console saying my array is undefined javascript
I've looked at many examples and I can't seem to figure out what I'm doing wrong here: 我看了很多例子,但似乎无法弄清楚我在做什么错:
var names_Array = [];
var names_List = new WinJS.Binding.List(names_Array);
names_List.push({ name: "Joe Dowling", image: "image/Joe Dowling.png", ClientID: "1234" });
window.localStorage.setItem('names_Array', JSON.stringify(names_Array));
var test = JSON.parse(window.localStorage.getItem('names_Array'));
console.log(test.name);
I'm getting undefined in the console , why it is happend? 我在控制台中变得不确定 ,为什么会发生呢?
You have two mistakes: 您有两个错误:
1) You just initialized the names_Array
and didn't added any elements to it. 1)您只是初始化了
names_Array
并且没有添加任何元素。 you are storing that empty array in localStorage. 您将空数组存储在localStorage中。
2) Since test
is an array of objects ( if you are pushing objects into it ), you have to access one specific object through index, or loop through the array to get members. 2)由于
test
是一个对象数组(如果将对象推入其中),则必须通过索引访问一个特定的对象,或者循环遍历该数组以获取成员。
This code should work: 此代码应工作:
var names_Array = [];
var names_List = new WinJS.Binding.List(names_Array);
names_List.push({ name: "Joe Dowling", image: "image/Joe Dowling.png", ClientID: "1234" });
window.localStorage.setItem('names_Array', JSON.stringify(names_List));
var test = JSON.parse(window.localStorage.getItem('names_Array'));
for( i in test ) console.log(test[i].name);
window.localStorage.setItem(
'names_Array',
JSON.stringify(['John Doe', 'Jane Doe'])
);
console.log(JSON.parse(window.localStorage.getItem('names_Array')));
Prints 版画
["John Doe", "Jane Doe"]
Maybe test.name
is getting in the way? 也许
test.name
?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.