gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 01:18:22 24 4
gpt4 key购买 nike

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

关于javascript - 浏览器本地存储无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54498175/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com