我正在尝试设置并从本地存储中获取项目,但是当我记录数据时,我得到[object Object]
我试图让这个对象的视图像这样{a:v,b:v} ......
这是代码:
var widgets = localStorage.getItem('widgets');
if (widgets == null) {
widgets = {
widget_lot : '',
widget_td : '',
widget_cwo : '',
widget_vehicles : '',
widget_take : ''
};
widgets.widget_lot = 0;
widgets.widget_td = 0;
widgets.widget_cwo = 1;
widgets.widget_vehicles = 0;
widgets.widget_take = 0;
localStorage.setItem('widgets', widgets);
}
console.log(widgets); //Logs "[object Object]"
答案 0 :(得分:15)
本地存储仅支持string
数据类型。所以你必须
在保存到LocalStorage之前将其转换为String
localStorage.setItem('key', JSON.stringify(data));
转换回JS对象,从LocalStorage读取
data = JSON.parse(localStorage.getItem('key');
如果是您的代码,则应为 -
var widgets = JSON.parse(localStorage.getItem('widgets'));
和
localStorage.setItem('widgets', JSON.stringify(widgets));
答案 1 :(得分:1)
您需要在将对象存储到存储之前对其进行字符串化,例如
localStorage.setItem('widgets', JSON.stringify(widgets));
localStorage将值存储为字符串,因此当您尝试将对象保存到toString()
时,将调用要存储的值的方法,因为您有一个对象,它将返回[object Object]
以同样的方式,getItem()返回一个字符串,将其转换为对象使用JSON.parse()
所以
var widgets = localStorage.getItem('widgets');
console.log('stored', widgets)
if (widgets == null) {
widgets = {
widget_lot: '',
widget_td: '',
widget_cwo: '',
widget_vehicles: '',
widget_take: ''
};
widgets.widget_lot = 0;
widgets.widget_td = 0;
widgets.widget_cwo = 1;
widgets.widget_vehicles = 0;
widgets.widget_take = 0;
localStorage.setItem('widgets', JSON.stringify(widgets));
} else {
widgets = JSON.parse(widgets)
}
console.log(widgets); //Logs "[object Object]"
演示:Fiddle
答案 2 :(得分:0)
或者你可以使用http://rhaboo.org并写:
store = Rhaboo.persistent("Widget Store");
if (store.widgets === undefined)
store.write('widgets', {
lot: 0,
td: 0,
cwo: 1,
vehicles: 0,
take: 0
});
else
alert("I remember! There are " + store.widgets.vehicles + " vehicles")
store.widgets.write('vehicles', store.widgets.vehicles+1);
BTW,我写了rhaboo。