当我将变量分配给另一个变量时,它是不是将它们链接在一起? [英] When I assign a variable to another variable does it not link them together?

查看:67
本文介绍了当我将变量分配给另一个变量时,它是不是将它们链接在一起?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到更多关于lodash _.clone的内容,我认为它是一个对象中的数据副本并创建了一个不同的对象。但是,当我在控制台中测试时,我注意到了这一点:

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. 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 

我期待看到的是b将是100有人可以帮我解释一下。

What I was expecting to see was that b would be 100. Can someone explain this for me.

更新:

这是我遇到的问题:

                $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

推荐答案

这就是变量在JavaScript和大多数语言中的工作方式。分配 b = a 将变量 a 分配给变量 b 。在您能够将变量设置为对另一个变量的引用的语言中,通常会有一个特定的语法来执行此操作; JavaScript没有此功能。

That's how variables work in JavaScript, and most languages. Assignment of b = a assigns the value of variable a to variable 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.

请注意,这可能会让人感到困惑,因为在对象的情况下,值是从分配的值 b 是对象的引用,但这仍然没有链接变量本身,只是将它们指向同一个对象。修改任一变量(通过赋值)都不会影响另一个变量,但是对象任何变量都会被两个变量镜像,因为它们同样指向同一个对象。

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. 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.

这篇关于当我将变量分配给另一个变量时,它是不是将它们链接在一起?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆