javascript 如何在localStorage中存储对象?

arknldoa  于 2023-01-04  发布在  Java
关注(0)|答案(2)|浏览(183)

我尝试从本地存储设置和获取项目,但当我记录数据时,我得到[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]"
c7rzv4ha

c7rzv4ha1#

本地存储只支持string数据类型。因此,您必须
1.在保存到LocalStorage之前将其转换为字符串

localStorage.setItem('key', JSON.stringify(data));

1.转换回JS对象,从LocalStorage阅读

data = JSON.parse(localStorage.getItem('key')); //forgot to close

如果是你的代码,应该是-

var widgets = JSON.parse(localStorage.getItem('widgets'));

以及

localStorage.setItem('widgets', JSON.stringify(widgets));
fjaof16o

fjaof16o2#

在将对象存储到存储器之前,需要将其字符串化,如

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

相关问题