localStorage和带有数组的Javascript对象,保存问题

时间:2012-03-20 16:15:35

标签: javascript arrays local-storage javascript-objects

我有以下组件:

patientDiseasesStorage = new Object()
patientDiseasesStorage['p158246547'] = [1, 3, 8, 2, 5] //and many more of this with different p-number

我现在尝试保存此对象/数组组合

localStorage.setItem('patientDiseasesStorage', JSON.stringify(patientDiseasesStorage));

但是当我尝试从localStorage读回来时,它没有正确的值:

patientDiseasesStorage = JSON.parse(localStorage.getItem('patientDiseasesStorage'));
patientDiseasesStorage['p158246547'] is now undefined and not the array.

我做错了什么?

2 个答案:

答案 0 :(得分:0)

如果p158246547是字符串而不是变量名,则它应该有引号:

patientDiseasesStorage['p158246547'] = [1, 3, 8, 2, 5] //and many more of this with different p-number

当你将它从localStorage拉回来时使用引号。

答案 1 :(得分:0)

您使用的浏览器是什么?最新的Chrome适合我。

var a = [1, 2,3]
var obj = {'a': a}
obj.a
> [1, 2, 3]
localStorage.setItem('obj', JSON.stringify(obj))
var obj2 = JSON.parse(localStorage.getItem('obj'))
obj2.a
> [1, 2, 3]