1
var array = [{}];

var obj = {
    name: "Fred X",
    age: 20
}

function x() {
    array[1].name = "Alice";
    array[1].age = 48;
}

array[0] = obj;
document.write(array[0].name + "=" + array[0].age, "<br>");
array[1] = obj;
x();
document.write(array[0].name, "=", array[0].age < br > ",array[1].name,"=",array[1].age);

I am trying to construct a shopping cart with an array of items (objects with properties) but it is not working. The code above illustrates the problem: when I try to read out the cart, all items appear like the last added one. What am i not getting here? Thanks in advance ...

Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63
Willem
  • 11
  • 2
  • 3
    Read [Javascript by reference vs. by value](https://stackoverflow.com/questions/6605640/javascript-by-reference-vs-by-value) – Satpal Jul 21 '17 at 12:37
  • Possible duplicate of [Javascript by reference vs. by value](https://stackoverflow.com/questions/6605640/javascript-by-reference-vs-by-value) –  Jul 21 '17 at 12:44

3 Answers3

0

You should check @Satpal's link as it illustrates the problem you're having: a reference issue.

When you create a variable, say obj, whenever you change it's value, it will be change wherever you have used it.

Try using a function to add something in the cart:

function addItemToCart(name, age) {
    array.push({ 
        name: name,
        age: age
    });
}

addItemToCart("Alice", 48);

array.forEach(cartItem => {
    document.write(cartItem .name + "=" + cartItem .age, "<br>");
});

Your code will work and look better than the way you did.

Also, you have a typo in your last line.

DontVoteMeDown
  • 21,122
  • 10
  • 69
  • 105
0

Hi I have updated your code, You have oen extra " inside your last line, I have updated your code, Please check below,

var array = [{}];
  var obj={
  name:"Fred X",
  age:20
  }
  function x(){
  array[1].name = "Alice";
  array[1].age = 48;
  }

  array[0]=obj;
  document.write(array[0].name+"="+array[0].age,"<br>");
  array[1]=obj;
  x();
  document.write(array[0].name,"=",array[0].age,"<br>",array[1].name+"="+array[1].age);

Also here is a samle screenshot of your code, Screenshot

Also one working codepen for your clarification

https://codepen.io/shohil06/pen/ZJzEJj

Hope it helps,

thank you

Community
  • 1
  • 1
SHOHIL SETHIA
  • 2,187
  • 2
  • 17
  • 26
0

var array = [{}];

var obj = {
    name: "Fred X",
    age: 20
}

function x() {
    array[1].name = "Alice";
    array[1].age = 48;
}

array[0] = obj;
console.log(array[0].name + "=" + array[0].age, "\n");
array[1] = obj;
x();
console.log(array[0].name,"=",array[0].age,"\n",array[1].name+"="+array[1].age);

Check this out.