1

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?

Paul Roub
  • 36,322
  • 27
  • 84
  • 93
sm12
  • 115
  • 2
  • 15
  • Use the other `for` loop `for(var i = 0; i < arr.length; i++)` and use `arr.push(10); arr.push(20);` instead of `arr[length+0]` – Lixus Sep 30 '17 at 14:38
  • 2
    `for (var ... in ...)` is only meant for objects: [Why is using “for…in” with array iteration a bad idea?](https://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-a-bad-idea) – Andreas Sep 30 '17 at 14:40
  • Do the additional elements **need** to be added during iteration? Why can't they be added first? – Alan Larimer Sep 30 '17 at 15:00
  • 1
    @AlanLarimer Most likely he's simplified the code in the question, and the real code is not adding constants like this. – Barmar Sep 30 '17 at 15:07
  • @Bamar Thanks, I understand that. In knowing the root issue or intent then perhaps an alternative solution can be found. – Alan Larimer Sep 30 '17 at 15:10
  • 1
    You should not use a `for` loop 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 a `for` loop, b) modify it in a `while` loop c) modify it through recursion. – Redu Sep 30 '17 at 17:59

2 Answers2

2

You could use a for statement and check the length while iterating the array.

With for ... in statement, iteration of new elements is not granted.

Properties added to the object over which iteration is occurring may either be visited or omitted from iteration. In general it is best not to add, modify or remove properties from the object during iteration, other than the property currently being visited.

var array = [1, 3, 8],
    i;

for (i = 0; i < array.length; i++) {
    console.log(array[i]);
    if (i === 0) {
        array.push(10, 20);
    }
}
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

You really shouldn't ever need to do this, there's probably a better method. But, if you absolutely have to, use a while loop instead:

var arr = [1, 2, 3];
var i = 0;
while (i < arr.length) {
  if( i == 0 ) {
    arr.push(10, 20);
  }
  console.log(arr[i]); // 1, 2, 3, 10, 20
  i++;
}
treyhakanson
  • 4,611
  • 2
  • 16
  • 33