push multiple array object into localhost?

天涯浪子 提交于 2019-12-25 06:09:19

问题


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

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

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


回答1:


It does replace the existing one.

Try this:

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.



来源:https://stackoverflow.com/questions/31353101/push-multiple-array-object-into-localhost

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!