0

I am trying to push objects to an empty array, where its x property value incremented on each loop. I used console.log(B.x) to check that it does iterate but even so, each object will have its x property value set to 300

n = 20, therefore, 100 (original x's value) + 10 (iteration) * 20 (loop) = 300

function createBlocks(n) {
  var blockArray = [];

  var B = {
    x: 100,
    y: 100,
    width: 35,
    height: 35,
    color: "brown"
  }

  for (var i = 0; i < n; i++) {
    blockArray.push(B);
    B.x += 10;
    console.log(B.x);
    console.log(blockArray[i]);
  }
  return blockArray;
}

I don't understand why all the objects have the same value (300) for its x's property.

1
  • Because objects are passed as reference not value. When you assign one object's value to another it will be referred not copied. Commented Nov 16, 2017 at 7:20

2 Answers 2

2

Because your object is single and you have multiple references to it. So why changing for one, it changes the actually object. You need to create separate objects for each item.

You can use object destructing to copy the properties from one object into a new object and push that temp object into the array.

const blockArray = [];

const B = {
  x: 100,
  y: 100,
  width: 35,
  height: 35,
  color: "brown"
}

for (var i = 0; i < 10; i++) {
  let temp = { ...B };
  blockArray.push(temp);   
  B.x += 10;
}
  
console.log(blockArray);

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

Comments

0

You could use the ES6 spread operator for this also:

function createBlocks(n) {
  const blockArray = [];

  const B = {
    x: 100,
    y: 100,
    width: 35,
    height: 35,
    color: "brown"
  };

  for (var i = 0; i < n; i++) {
    const temp = { ...B }; // object spread
    blockArray.push(temp);
    B.x += 10;
  }
  return blockArray;
}

createBlocks(20);

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.