浏览器的本地存储无法正常工作

时间:2019-02-02 22:35:24

标签: javascript arrays json local-storage

我正在尝试使用浏览器的本地存储来存储阵列,但是它不能正常工作。当我对其进行测试时,由于某种原因,该数组的两个索引都返回“ null”。我在做什么错了?

window.localStorage.clear();
var requesterID = "ABC";
var title = "title";

if (window.localStorage.getItem("alreadyGotLastForAWeek") == null) {
window.localStorage.setItem("alreadyGotLastForAWeek", JSON.stringify(["placeHolder1"]));
} //end of if (window.localStorage.getItem("alreadyGotLastForAWeek") == null)

window.localStorage.setItem("alreadyGotLastForAWeek", JSON.stringify(JSON.parse(window.localStorage.getItem("alreadyGotLastForAWeek")).push(requesterID+title)));
var tempArray = JSON.parse(window.localStorage.getItem("alreadyGotLastForAWeek"));

console.log(tempArray[0]);
console.log(tempArray[1]);

预期结果:

placeHolder1
ABCtitle

实际结果:

null
null

1 个答案:

答案 0 :(得分:2)

之所以会这样,是因为Array.prototype.push将元素添加到了数组中,并且返回了数组的新长度,就像您读到here一样。

您可以拆分功能:

const array = JSON.parse(window.localStorage.getItem("alreadyGotLastForAWeek"));
array.push(requesterID+title);
const stringifiedArray = JSON.stringify(array);

window.localStorage.setItem("alreadyGotLastForAWeek", stringifiedArray);

或者您可以使用Array.prototype.concat代替push

window.localStorage.setItem("alreadyGotLastForAWeek", JSON.stringify(JSON.parse(window.localStorage.getItem("alreadyGotLastForAWeek")).concat([requesterID+title])));