I have a JavaScript array of length 3
arr = [1, 3, 8];
Is there a way to add elements to arr while I am iterating over it? I want to insert two values 10 and 20 into the existing arr. Can I do it like this? The newly added elements, 10 and 20, must also be looped over in the same for in loop.
for(var i in arr) {
if( i == 0 ) {
arr[length + 0] = 10;
arr[length + 1] = 20;
}
}
Or, what is the correct way to add elements to an array while iterating and making sure that the newly added elements will also be looped over?
forloopfor(var i = 0; i < arr.length; i++)and usearr.push(10); arr.push(20);instead ofarr[length+0]for (var ... in ...)is only meant for objects: Why is using “for…in” with array iteration a bad idea?forloop to mutate the entity you are playing with in computer science. You best never do it but if you really need to... a) prepare your array in advance and then iterate by aforloop, b) modify it in awhileloop c) modify it through recursion.