我正在尝试使用浏览器的本地存储来存储数组,但它无法正常工作。当我测试它时,由于某种原因,它为数组的两个索引返回“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
发生这种情况是因为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])));