0

is there a way to loop an array in "real time" in Javascript or using JQuery? What I mean is to create a loop that reads the array content without caching it before starting the loop, for example if I do this.

var array = [{'hi':0},{'how':1},{'are':2},{'you':3}];

for(var i=0;i < array.length;i++){
  console.log(i);
  if(i == 2){
    array.push({'?':4});
  }
}
console.log(array);

The loop will output only 4 values but it already has 5 values before finishing the loop

I would like to also loop the new values inserted while the loop is running.

For more clarification, I need to do this because I am building a web app that creates a queue before submitting data to the server, a loop submits the data in the array but this array can also be updated in the process by other functions

Thanks!

6
  • 4
    It output 5 values. Your question is not clear. Commented Aug 17, 2018 at 13:45
  • @AnkitAgarwal his question is clear to me - he wants to mutate the array during the loop, and wants the loop to keep going while insertions are made to the array Commented Aug 17, 2018 at 13:46
  • @duxfox-- yes, but he said that it was logging just 4 values, but it's not true, the loop is logging the entire array including the value added inside the loop, so 5 values Commented Aug 17, 2018 at 13:47
  • Are you forgetting that index starts at zero and 4 is actually the 5th iteration? Commented Aug 17, 2018 at 13:47
  • Add more logging details to your code and you will see the index you added at the end of the loop. console.log(i, JSON.stringify(array[i])); Commented Aug 17, 2018 at 13:50

1 Answer 1

2

Your code works as you want. It works because at each iteration, you evaluate i against array.length, so even if the length changes during one iteration, the loop will adapt accordingly.

It would not work if you used :

for(var i=0, j=array.length; i<j; i++){

because in this case, the length is stored in j, and then j doesn't change, regardless of what happends in the loop.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.