繁体   English   中英

For-each 循环不迭代从本地存储读取的数组

[英]For-each loop not iterating over an array that is read from local storage

收到一条错误消息,指出“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; 
            }
        }

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

解析后从 localStorage 检索时,您的 taskOuput 是 object; 使用for of循环是不可迭代的

尝试将代码更新为此,

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM