Skip to content
Advertisement

javascript pushing object to the array at for loop changes the front components

I’m trying to push different objects at each time, but it changes the front components while looping the for loop. Here is my code.

JavaScript

And my result looks like this.

JavaScript

I can’t understand why at 2th loop, responseArray[0] changes {"data":0} to {"data":1}. I want my responseArray looks like [{"data":0},{"data":1"},...]. What’s happening on Array.push(object) at javascript? And how could I get the result what I want?

Advertisement

Answer

It’s because you’re passing the result variable as a reference, everytime the result.data changes, so as the pushed items on the responseArray will be changed also.

So to avoid that. do this instead:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement