Reputation: 1053
I'm trying to add an item from a loop to beginning of my 'storedCompletion' array but for some reason it just continues looping and crashes the browser.
I don't understand why because after it's looped through each object in the array it checks to see if the object id matches up with the list items element id so it should run on one occasion?
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));
Upvotes: 1
Views: 1067
Reputation: 26617
You're looping while f < storedCompletion.length
, but you are increasing that length inside of your for loop.
Because you are unshift()
-ing, the item goes to the beginning. That means everything gets push over one. So, when f++
happens, it looks at the same item. Thus, it'll keep adding forever.
Step through it a couple of times:
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
And so on forever. You're getting in an infinite loop.
I'm not sure what exactly you're trying to do, but what you might want to do is make a new array to add the new items to, and leave storedCompletion
alone, then set the new array to storedCompletion
.
Upvotes: 2