带有数组的localStorage和Javascript对象,保存问题
我有以下几个部分:带有数组的localStorage和Javascript对象,保存问题,javascript,arrays,local-storage,javascript-objects,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(patientDiseasesStora
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.
我做错了什么?如果
p158246547
是一个字符串而不是变量名,那么应该在其周围加引号:
patientDiseasesStorage['p158246547'] = [1, 3, 8, 2, 5] //and many more of this with different p-number
将其从本地存储中取出时也要使用引号。您使用的浏览器是什么?最新的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]
p158246547
确实是一个变量吗?如果是,它在两种情况下的值是否相同?我有很多这样的ID。我想存储这些ID的数组,稍后再从本地存储中获取具有相同ID的数组,但实际ID是否存储在名为p158246547
的变量中?或者ID本身应该是p158246547
?ID是p158246547。问题不在于存储和接收对象中的数组。问题是:将对象存储在localstorage中并重新接收后,我无法正确还原它以接收我的数组。我更正了id值的引号。对象中的存储和读取正在工作。仅当我从localStorage还原对象时,它不再工作。当我使用语法object.newname为对象分配新值时,它才工作。但是,当新值的名称存储在变量中时,如何为对象赋值呢?@user1031990:我看不出问题所在-如果我将其更改为使用var obj=new object();obj['a']=a
一切仍然一模一样——我一字不差地复制并粘贴了您的代码,效果很好。。。你能做一个例子来说明这个问题吗?