我正在尝试将一个循环中的项目添加到我的“storedCompletion”数组的开头,但由于某种原因它只是继续循环并使浏览器崩溃。
我不明白为什么,因为在遍历数组中的每个对象后,它会检查对象 ID 是否与列表项元素 ID 匹配,所以它应该只运行一次?
JS
if(localStorage) {
var storedCompletion = JSON.parse(localStorage.getItem('todos'));
}
for(var f=0; f<storedCompletion.length; f++) {
if(storedCompletion[f].id == listItem.id) {
storedCompletion[f].completed = false;
console.log(storedCompletion);
storedCompletion.unshift(storedCompletion[f]);
console.log(storedCompletion);
}
}
localStorage.setItem('todos', JSON.stringify(storedCompletion));
最佳答案
你正在循环 f < storedCompletion.length
,但您正在增加 for 循环内的长度。
因为你是unshift()
-ing,项目转到开头。这意味着一切都会被推到一个之上。所以,当f++
碰巧,它看的是同一个项目。因此,它将永远添加。
通过它几次:
s = [0]; // s.length === 1, f < s.length
f = 0;
// unshift s, f++
s = [1,0]; // s.length === 2, f < s.length
f = 1; // still points at 0
// unshift s, f++
s = [2,1,0]; // s.length === 3, f < s.length
f = 2; // still points at 0
以此类推。你进入了一个无限循环。
我不确定你到底想做什么,但你可能想要做的是创建一个新数组来添加新项目,然后离开 storedCompletion
单独,然后将新数组设置为 storedCompletion
.
关于javascript - Unshift 连续循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45042511/