admin管理员组

文章数量:1319023

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"]

本文标签: Updating localstorage arrays in JavascriptStack Overflow