【问题标题】:Why variables are not automatically updated in Java Script? (scope? ) [duplicate]为什么 Java Script 中的变量不会自动更新? (范围?)[重复]
【发布时间】:2018-03-26 11:06:13
【问题描述】:

我有以下代码:

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 记录到控制台时,可能会认为 x 为 500,但它仍然是 20。Console.log(obj.speed) 结果为 500。

你能告诉我为什么会这样吗?

我知道如果我交换它们的位置:var x 声明和 obj.speed = 500,它将指向 500。就像 y 变量一样

但是为什么呢?代码在记录 x 变量之前是否不检查它的最后一个值?

【问题讨论】:

  • 你复制变量的值而不是引用
  • “人们会认为 x 会是 500” – 不,不会。您正在将值 20 分配给一个变量,然后您正在更新一个不同的变量……
  • 不,您已为x 分配了一个值,而不是引用类型
  • var x = 20;一模一样
  • 参见例如codeburst.io/…

标签: javascript variables


【解决方案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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-21
    • 2019-08-19
    • 2012-07-24
    • 2019-06-22
    • 1970-01-01
    • 2017-09-28
    • 2013-02-23
    相关资源
    最近更新 更多