Reputation: 255
I have a problem with the splice method. In the script below, if I set the second argument of splice to '0' it crashes my browser. If I set to any other value that is greater than '0' it works just fine.
Why is this happening?
Thanks,
And the code:
function f (x) {
var d = x.toString().split("");
for (i=0; i<d.length; i++){
if (Number(d[i])%2===0){
d.splice(i, 0, "drum");
}
}
return d;
};
Upvotes: 2
Views: 925
Reputation: 28548
Its an infinite loop and each time drum
is getting inserted to array increasing its length.
Splice()
insert the item to array so you are inserting new item.
first loop:
8,8,8
i
is 0 //d[0] is 8if (Number(d[i])%2===0)
is true
drum
inserted Now Array is drum,8,8,8
second loop:
drum,8,8,8
i
is 1 //d[i] is 8if (Number(d[i])%2===0)
is true
drum
inserted Now Array is drum,drum,8,8,8
and it goes on....
Upvotes: 1