不加速连续循环?

时间:2017-07-11 18:55:05

标签: javascript

我试图将一个项目从一个循环添加到我的“存储完成”的开头。数组,但由于某种原因,它只是继续循环并崩溃浏览器。

我不明白为什么,因为在它循环遍历数组中的每个对象后,它会检查对象id是否与列表项元素id匹配,以便它应该运行一次? / p>

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));

1 个答案:

答案 0 :(得分:2)

你在f < storedCompletion.length时循环,但是你在for循环中增加了这个长度。

因为你是unshift(),所以该项目开始了。这意味着一切都会超越一个。因此,当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