我目前正在做一个项目,在这个项目中我必须从 localStorage 加载一个数组,然后从这个循环中通过它来生成元素。
我的保存过程按预期工作,但是当它归结为加载它时 - 我收到以下错误。
TypeError: undefined is not a function (evaluating 'mainInfo.forEach')
您可以在下面看到引发此错误的代码。
var mainInfo = [];
var subInfo = [];
mainInfo = localStorage.StaffAppMainList;
subInfo = localStorage.StaffAppSubList;
finalOutput = "";
console.log(mainInfo.length);
mainInfo.forEach(function(item) {
var theTitle = item.title;
var url = "Pages/SubInfo.html?info=" + theTitle;
finalOutput = finalOutput + "<li><a href='" + url + "'>" + item.title + "</a></li>";
$("#homeList").html(finalOutput).listview().listview("refresh");
});
抛出错误的行是-
mainInfo.forEach(function(item) {
目前我不确定是什么导致了这个错误,所以任何建议将不胜感激。
最佳答案
Local storage (aka Web Storage)只存储字符串。如果你想持久化一个数组,你可以在存储之前对其进行 JSON 编码,并在检索时对其进行解码。
// storing
var mainInfo = [];
localStorage.setItem("StaffAppMainList", JSON.stringify(mainInfo));
// retrieving
mainInfo = JSON.parse(localStorage.StaffAppMainList);
如果您尝试存储任何非字符串的内容,将存储一个空字符串,因此会出现错误,因为字符串没有 forEach
方法。
关于Javascript - 未定义不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24589582/