[英]When I assign a variable to another variable does it not link them together?
I was trying to find out more about the lodash _.clone which I thought made a copy of the data in an object and created a different object. 我试图找到有关lodash _.clone的更多信息,我认为它在对象中复制了数据并创建了另一个对象。 However when I was testing in the console I noticed this:
但是,当我在控制台中进行测试时,我注意到了这一点:
var a = 88
undefined
var b = a
undefined
console.log(b)
88 VM1010:2
undefined
var a = 100
undefined
console.log(b)
88
What I was expecting to see was that b would be 100. Can someone explain this for me. 我期望看到的是b为100。有人可以帮我解释一下。
Update: 更新:
Here's the problem I had: 这是我遇到的问题:
$scope.grid.data = result;
$scope.grid.backup = _.clone(result);
Here it appears that when I change a value inside the data object then a corresponding value changes inside the .backup object 在这里,似乎当我更改数据对象内部的值时,.backup对象内部的对应值也发生了变化
That's how variables work in JavaScript, and most languages. 这就是变量在JavaScript和大多数语言中的工作方式。 Assignment of
b = a
assigns the value of variable a
to variable b
. b = a
的赋值将变量a
的值赋给变量b
。 In languages where you're able to set a variable as a reference to another variable, there is usually a specific syntax for doing so; 在能够将变量设置为对另一个变量的引用的语言中,通常使用特定的语法来进行设置。 JavaScript does not have this feature.
JavaScript没有此功能。
Note that this can appear confusing because, in the case of objects, the value being assigned from a
to b
is a reference to the object, but this still doesn't "link" the variables themselves, it just "points" them to the same object. 请注意,这可能会造成混淆,因为在对象的情况下,从
a
到b
分配的值是对该对象的引用,但这仍然不会“链接”变量本身,而只是将它们“指向”到同一对象。 Modifying either variable (via assignment) will not affect the other variable, but any changes the object through either variable will be mirrored by both variables because, again, they point to the same object. 修改任何一个变量(通过赋值)都不会影响另一个变量,但是通过两个变量对对象进行的任何更改都将被两个变量镜像,因为它们再次指向同一对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.