Updating localstorage arrays in Javascript

不问归期 提交于 2021-02-05 07:25:08

问题


I'm trying to store and update an array in the localstorage using JSON.parse/stringify. But it doesn't seem to be working.

    yesArray = JSON.parse(localStorage.getItem(yesArray));
    yesArray.push("yes");
    localStorage.setItem("yesArray", JSON.stringify(yesArray));

Am I all wrong with this?


回答1:


This seems to be the problem with passing the key of local storage without quotes.

While reading from local storage use the key as argument as it stores the value as key/value pairs.

yesArray = JSON.parse(localStorage.getItem("yesArray"));



回答2:


Missing quotes around yesArray in the first line?

yesArray = JSON.parse(localStorage.getItem('yesArray'));

Sample:

var yesArray = [];
localStorage.setItem('yesArray', JSON.stringify(yesArray));
yesArray = JSON.parse(localStorage.getItem('yesArray'));
yesArray.push('yes');
localStorage.setItem('yesArray', JSON.stringify(yesArray));
JSON.parse(localStorage.getItem('yesArray')); // Returns ["yes"]


来源:https://stackoverflow.com/questions/40985620/updating-localstorage-arrays-in-javascript

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