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. you are storing that empty array in 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.
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?
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.