admin管理员组

文章数量:1418113

In javascript, why doesn't the list update with a variable?

var x = 5;
var l = [x];
x += 6;

why is l still 5 and not 11? Is there a way to get it to update with the variable?

In javascript, why doesn't the list update with a variable?

var x = 5;
var l = [x];
x += 6;

why is l still 5 and not 11? Is there a way to get it to update with the variable?

Share Improve this question edited Apr 28, 2017 at 14:13 Suresh Atta 122k38 gold badges206 silver badges315 bronze badges asked Apr 28, 2017 at 14:06 user7903682user7903682 3191 gold badge4 silver badges18 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 3

l is a list of values, not a list of pointers. To simulate what you're trying to do, you could store mutable objects and mutate them.

var x = { val: 5 };
var l = [x];
x.val += 6;
console.log(l); // [{ val: 11 }]

Unlike objects, primitive values are immutable. Once you change them you have to assign them back.

var l = [x];
x += 6;
var l = [x]; // new value updation.

Since you don't hold the reference to array, assigned back with a new array.

If you hold a reference to the array, you can just update the variable instead of whole array.

var arr = [x];
var l =  arr;
x += 6;
arr[0] = x; // new value updation at position 0.

My understanding is that this is actually very simple:

Javascript is always pass by value, but when a variable refers to an object (including arrays), the "value" is a reference to the object.

Changing the value of a variable never changes the underlying primitive or object, it just points the variable to a new primitive or object.

However, changing a property of an object referenced by a variable does change the underlying object.

only way to update array value is to reassign it.

A variable won't update itself. You have to redefine it.

var x = 5;
var l = [x];
x += 6; // x has changed but l has not, because you defined it to be old x
l = [x] // redefine it to be new x
console.log(l);

var x = 5;
x +=6; 
var l = [x];

With this var l will be up to date

本文标签: javascriptArray value not updated after changing variable valueStack Overflow