Ngoan Tran
Ngoan Tran

Reputation: 1527

Node.js control flow

I'm new with nodejs and I'm really confused in the asynchronous.

I tried with the sample code to store item to an array in a for loop:

var item = {};
var array = [];
for (var j = 1; j < 5; j++) {
  item.test = j;
  array.push(item);
}

I expected the result of array to be:

[{test: 1}, {test: 2}, {test: 3}, {test: 4}]

But i got:

[{test: 4}, {test: 4}, {test: 4}, {test: 4}]

If i just push j to array, it's fine.

var array = [];
for(var j = 1; j < 5; j++) {
  array.push(j);
}

The result is:

[1, 2, 3, 4]

I would very appreciate any explanation why this happens.

Upvotes: 1

Views: 185

Answers (5)

Larry Turtis
Larry Turtis

Reputation: 1916

You can solve this just by declaring item inside the scope of the loop, so it's a new object each time.

const array = [];

for(let j = 1; j < 5; j++){
   var item = {test: j};
   array.push(item);
}

Upvotes: 1

vipin
vipin

Reputation: 367

You are trying to modify the same object while looping. Please create the object in your looping statement and push it to your array.

var array = [];

for (var j = 1; j < 5; j++) {
  var item = {};
  item.test = j;
  array.push(item);
}

for (var j = 0; j < array.length; j++) {
  console.log(array[j]);
} 

Upvotes: 0

Florian Neumann
Florian Neumann

Reputation: 5857

In each iteration you're pushing the same object-instance of item into the array. Which ends up in an array of references to item which contains test: 5 from the last assignment.

You need to create different objects in each iteration to preserve different attributes:

for (var j = 1; j < 5; j++) {
   array.push({test: j});
}

Upvotes: 1

abdulbari
abdulbari

Reputation: 6242

Your item object is overriding with last item. try to reinitialize your object

Try this

  

  var item = {};
  var array = [];
  for(var j =1; j<5; j++){
    item.test = j;
    array.push(item);
    item={};
  }
  console.log(JSON.stringify(array))

Upvotes: 1

Denis Lisitskiy
Denis Lisitskiy

Reputation: 1345

Try this one

var array = [];
for(var j =1; j<5; j++){
  var item = {};
  item.test = j;
  array.push(item);
}

Upvotes: 1

Related Questions