最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Updating localstorage arrays in Javascript - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question asked Dec 6, 2016 at 0:04 SausejiiSausejii 631 gold badge1 silver badge5 bronze badges 2
  • What error do you see in console? – Ajay Narain Mathur Commented Dec 6, 2016 at 0:07
  • 5 getItem(yesArray) -> getItem("yesArray") typo? – Alexander O'Mara Commented Dec 6, 2016 at 0:08
Add a ment  | 

2 Answers 2

Reset to default 3

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"));

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"]
发布评论

评论列表(0)

  1. 暂无评论