【问题标题】:For-each loop not iterating over an array that is read from local storageFor-each 循环不迭代从本地存储读取的数组
【发布时间】:2020-05-26 20:25:04
【问题描述】:

收到一条错误消息,指出“taskOutput 不可迭代”。数组如下所示:

const taskOutput = JSON.parse(window.localStorage.getItem("taskList")) || [];

循环如下所示:

 for (const task of taskOutput) {
        const taskEl = document.createElement("div");
        const {participant, duetime, description} = task;

        // PROGRESSION-BAR
        let newDiv = document.createElement("div"); 
        let newBtn = document.createElement("button");
        let btnText = document.createTextNode("Fullfør");
        newBtn.appendChild(btnText);

        newDiv.style.border = "3px solid black";
        newDiv.style.height = "10px";
        newDiv.style.backgroundColor = task.color; 

        newBtn.onclick = function() {
            if(task.color === "red"){
                task.color = "green"; 
                localStorage.setItem('taskList', JSON.stringify(taskOutput)); 

            }
            else if(task.color === "green"){
                task.color = "red"; 
                localStorage.setItem('taskList', JSON.stringify(taskOutput)); 
                newDiv.style.backgroundColor = task.color; 
            }
        }

【问题讨论】:

  • 这是 150 多行代码要阅读!你要问的是花 1 个小时来阅读和理解你所做的事情,再花 1 个小时来做​​出答案……你必须做出一个合成的、最小的、可重现的例子来说明你正在寻找的东西有答案,并遵循 SO 建议 stackoverflow.com/help/minimal-reproducible-example
  • 感谢您为我提供了正确的约定来发布问题,Jojo 先生。我会编辑它
  • 你能说明你在执行这一行时得到了什么价值吗console.log(taskOutput)
  • {类别:“工作”,参与者:“dasfs”,到期时间:“0005-12-31”,描述:“adsfsg”,颜色:“红色”}我正在将对象传递给本地存储
  • 这不是一个数组:/您的本地存储显然包含一个任务,而不是一组任务。

标签: javascript arrays local-storage


【解决方案1】:

for...of 语句创建一个循环遍历可迭代对象,包括:内置 String、Array、类数组对象。

你的taskOuput是解析后从localStorage中检索的对象;使用 for of 循环是不可迭代的

尝试将代码更新为此,

const taskList = JSON.parse(window.localStorage.getItem("taskList")) 
const taskOutput = taskList ? [taskList] : [];

【讨论】:

  • 很好,很乐意提供帮助:)
  • @LaurentBaj 请求您接受答案,因为它对您有用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-08
  • 1970-01-01
  • 2015-11-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多