2

Here is the code i have:

let testp = {
  value: ''
}
let data = [];
for (let i = 0; i < 5; i++) {
  testp.value = i;
  data.push(testp);
}

console.log(data)

The data return is:

[ { value: 4 },
  { value: 4 },
  { value: 4 },
  { value: 4 },
  { value: 4 } ]

why? I think the result is like this:

[ { value: 0 },
  { value: 1 },
  { value: 2 },
  { value: 3 },
  { value: 4 } ]
RobG
  • 142,382
  • 31
  • 172
  • 209
Vsking
  • 21
  • 1
  • assigning testp.value inside loop was causing the problem – user93 May 12 '17 at 01:36
  • 3
    `testp` is a reference to the javascript object; when you call `data.push(testp)`, you're merely adding to the array another reference to that same object. not a copy of the current state of the object – Hamms May 12 '17 at 01:38
  • 1
    You're getting `4` for every value, because JavaScript passes objects by reference, not by value. Thus you're modifying the same object on every iteration of the loop, not a different object. – fubar May 12 '17 at 01:38
  • 1
    @fubar—well, it's actually always by value, just that for objects (or [*non-primitives*](http://ecma-international.org/ecma-262/5.1/#sec-4.3.2)), the value held by a variable is a reference. – RobG May 12 '17 at 01:44
  • Probably a duplicate of [*javascript assignment operator array*](http://stackoverflow.com/questions/13050279/javascript-assignment-operator-array). – RobG May 12 '17 at 01:48
  • you are editing the same address space. Objects are copied by reference. – Rafael May 12 '17 at 01:49
  • @RobG the phrase 'copy by reference' is a common expression intending that the memory address is the only thing copied. There was no need to boast your arrogance. – Rafael May 12 '17 at 01:51

2 Answers2

2

You're pushing a reference to the object testp into the array 5 times, editing the value of value each time.

Here's another example:

let foo = { 'a': 1 };
let bar = [foo, foo, foo];
foo.a = 2;
console.log(foo[2]);
// 2

The array bar contains three references to foo. Changing the content of the object will change the content of the object everywhere it is referenced.

If you want new objects you have to create them somewhere. For example:

// Function that constructs the new objects
let foo = (value) => { return { "value": value } };
let data = [];

for (let i = 0; i < 5; i++) {
   data.push(foo(i));
}
Hamish
  • 22,860
  • 8
  • 53
  • 67
1

Assigning testp.value inside the loop was causing the problem.Instead you could do

let testp = {
  value: ''
}
let data = [];
for (let i = 0; i < 5; i++) {
  data.push({
    value: i
  });
}

console.log(data)
user93
  • 1,866
  • 5
  • 26
  • 45