且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

当我将变量分配给另一个变量时,它是不是将它们链接在一起?

更新时间:2023-02-11 20:04:27

这就是变量在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.