Updating localstorage arrays in Javascript

前端 未结 2 1251
挽巷
挽巷 2021-01-21 18:19

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(localStora         


        
2条回答
  •  南方客
    南方客 (楼主)
    2021-01-21 18:44

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

提交回复
热议问题