问题
(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