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?
5 Answers
Reset to default 3l
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
版权声明:本文标题:javascript - Array value not updated after changing variable value - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745281012a2651424.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论