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 } ]
7
  • assigning testp.value inside loop was causing the problem Commented May 12, 2017 at 1: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 Commented May 12, 2017 at 1: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. Commented May 12, 2017 at 1:38
  • 1
    @fubar—well, it's actually always by value, just that for objects (or non-primitives), the value held by a variable is a reference. Commented May 12, 2017 at 1:44
  • Probably a duplicate of javascript assignment operator array. Commented May 12, 2017 at 1:48

2 Answers 2

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));
}
Sign up to request clarification or add additional context in comments.

Comments

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)

1 Comment

Can you explain the reason why assigning inside of the loop is causing the problem?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.