Search code examples
javascriptloopsfor-in-loop

JavaScript : Iterate pushed elements in a same loop


How to iterate pushed value as well in a same loop.

I have one array like,

var arrays = [
    "hii",
    "hello"
];

I iterate using for in with push,

for (var index in arrays) {
    arrays.push(arrays[index] + " world");
    console.log(arrays[index]);
}
console.log(arrays);

Output :

hii
hello
Array(4): 0 : "hii", 1 : "hello", 2 : "hii world", 3 : "hello world"

jsFiddle.

Question : How do I iterate pushed element and iterate within same loop ?


Solution

  • Edit: OP edited the question to include pushed elements too in the iteration

    If you want to include the pushed elements during the iteration (which you claim to do conditionally to prevent infinity), you can use for loop with Array.length.

    for (var i = 0; i < arrays.length; i++) {
    
        if (some_condition)
           arrays.push(arrays[i] + 'world'); 
    
    }
    

    The loop will always try to go up to the new length.


    Previous answer:

    The Array.forEach method doesn't apply the iterator to the elements those are pushed during the iteration.

    const arrays = [
        "hii",
        "hello"
    ];
    
    arrays.forEach((e, i, a) => {
       a.push(e + ' world')
    
    });
    
    
    console.log(arrays)