简体   繁体   English

赋值后变量值未更新

[英]Value of variable not getting updated after assignment

var a = 2;
var b = a;

console.log( b ); //2

a= 5;

console.log( b ); //2

Q: Why variable 'b' is getting value 2 even when variable 'a' is assigned a different value 问:为什么即使变量“ a”被分配了不同的值,变量“ b”却获得了值2

console.log(b)返回2因为当您访问基本类型时,您将直接使用其值。

Cause numbers are immutable. 原因编号是不变的。

Changing an immutable value, replaces the original value with a new value, hence the original value is not changed (thats why b = 2 ). 更改不可变值,将原始值替换为新值,因此不会更改原始值(这就是b = 2 )。

If you need a reference, use object and/or arrays var a ={value: 2}, b = a a.value = 3 // also changes the value of be, since it can mutate 如果需要引用,请使用对象和/或数组var a ={value: 2}, b = a a.value = 3 // also changes the value of be, since it can mutate

在javascript中,图元(数字,布尔值,字符串)由值分配,只有对象由引用分配。

In Javascript, integers are immutable . 在Javascript中,整数是immutable It means that the object's value once assigned cannot change. 这意味着对象的值一旦分配就不能更改。 When you do 当你做

a=5;
b=a;

It is true that both are names of the same object whose value is 5 . 的确,两者都是同一个对象的名称,其值为5 Later when you do - 稍后,当您-

a=2

It assigns the reference a a new object whose value is 2. So essentially a now points to a new object. 它为引用分配a值为2的新对象。因此,基本上a现在指向一个新对象。 Ans both objects exist. Ans两个对象都存在。

For a better understanding you can refer to this link 为了更好的理解,您可以参考此链接

When doing Assignment of primitive values in javascript: 在javascript中进行原始值的分配时

It's important to point out that this assignment does not tie a and b together. 重要的是要指出,该分配不会将ab捆绑在一起。 In fact all that happened was that the value from a was copied into b , so when we go to change a we don't have to worry about affecting b . 事实上所发生的一切是从价值a被复制到b ,所以当我们去改变a我们不担心影响b This is because the two variables are backed by two distinct memory locations – with no crossover. 这是因为这两个变量由两个不同的内存位置支持-无交叉。

In brief way: 简而言之:

When you assign b = a 当您分配b = a

Actually you didn't copy the reference of a variable and make b point to the same variable location in memory. 其实你没有复制的引用a变量,并b指向内存中的同一个变量的位置。

You only copy the value of a variable and put it in new variable b with different memory location. 仅复制的价值a变量,并把它放在新的变量b具有不同的存储位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM