I'm having trouble populating an array:
var arr2 = ["x", "y", "z"];
I want to insert a random number/value between each original value using a for loop, like this:
for (let i = 1; i < arr2.length; i+2) {
arr2.splice(i, 0, Math.random());
}
But my browser freezes because the length of arr2 changes with every splice, creating an infinite loop. I tried another approach:
var len = arr2.length;
for(let j = 1; j < len; j+2) {
arr2.splice(j, 0, Math.random());
}
Now things are not working as expected. I suspect that len
is changing again.
I need to increment j
by two because after the first splice, arr2 looks like this:
["x", Math.random(), "y", "z"];
However, since j = 3
and the condition is j < len
, the only explanation is that len
is being modified once more.
Any insights would be appreciated. Ultimately, I want the array to end up like this:
arr2 = ["x", Math.random(), "y", Math.random(), "z"];