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?