Question

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;
};
Was it helpful?

Solution

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:

  • Array is 8,8,8
  • i is 0 //d[0] is 8
  • Condition if (Number(d[i])%2===0) is true
  • drum inserted Now Array is drum,8,8,8

second loop:

  • Array is drum,8,8,8
  • i is 1 //d[i] is 8
  • Condition if (Number(d[i])%2===0) is true
  • drum inserted Now Array is drum,drum,8,8,8

and it goes on....

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top