将多个数组对象推入localStorage? [英] push multiple array object into localStorage?

查看:265
本文介绍了将多个数组对象推入localStorage?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(function{
    var array = localStorage.getItem('id') || [];
    obj = {};
    obj.id = 1;
    array.push(obj);

    localStorage.setItem('id', JSON.stringify(array));
}();

为什么在我的localStorage中它没有两次插入obj?我看到它取代了现有的.

why in my localStorage it doesn't insert the obj twice? I'm seeing it replace the existing one.

推荐答案

它确实替代了现有的解决方案.

It does replace the existing one.

尝试一下:

if(localStorage.getItem('id')){  array = JSON.parse(localStorage.getItem('id')) } else {
var array = []; }
obj = {};
obj.id=1;
array.push(obj);

localStorage.setItem('id',JSON.stringify(array));

每次添加时,都会先获取本地存储项,然后再添加并放回原位.

Everytime you are adding it first gets the localstorage item and then adds to it and puts it back.

这篇关于将多个数组对象推入localStorage?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆