我有以下代码:
var obj = {
car: "volvo",
speed: 20
};
var x = obj.speed;
obj.speed = 500;
console.log(x);
console.log(obj.speed);
obj.speed = 1000;
var y = obj.speed;
console.log(y);
当你将它登录到控制台时,人们会期望x为500,但它仍然是20. Console.log(obj.speed)导致500。
你能告诉我为什么会这样吗?
据我所知,如果我交换他们的地方:var x declaration和obj.speed = 500,它将指向500.就像y变量一样
但为什么呢?在记录之前,代码是否不检查x变量的最后一个值?
答案 0 :(得分:1)
当您将x
分配给obj.speed
时,它类似于为原始变量分配值。
如果您将obj
的值分配给变量y
,那么它将会更新,因为它将引用相同的内存位置。
var obj = {
car: "volvo",
speed: 20
};
// Object is a referece data type.
// But you are assigining value of obj.speed which is primitive to the the x
// Hence value of x won't change even if you change the value of obj.speed.
var x = obj.speed;
obj.speed = 500;
console.log(x);
// But if you assign the value of object to another variable `y`
// Now, y will be pointing to the same memory location as that of obj
// If you update the obj, then the value of y will also get updated
var y = obj;
obj.speed = 1000;
console.log(y);
console.log(obj);