且构网

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

一行中的多个变量赋值

更新时间:2023-11-22 13:37:52

简短的回答是,该语句将 5 分配给4个变量中的每一个 a b c d 。但是,与上述内容相反,不会将 5 分配给 d ,然后是 d 到 c ,但它会从右侧开始为每个变量分配相同的值。为了更清楚,你的陈述:

The short answer is yes, that statement will assign 5 to each of 4 variables a, b, c and d. But, contrary to what was said, doesn't assign 5 to d, and then the value of d to c, but it will assign the same value to each variables, starting from the right-hand side. To be more clear, your statement:

var a, b, c, d;
a = b = c = d = 5;

相当于:

var d = 5;
var c = 5;
var b = 5;
var a = 5;

到:

var d = 5;
var c = d;
var b = c;
var a = b;

这是一个微妙但重要的区别:在第一种情况下,JavaScript只是设置所有变量的值。在第二种情况下,JavaScript 设置所有变量的值获取三个变量的值( a 未在任何地方分配。)

It's a subtle but important difference: in the first case, JavaScript just sets a value to all the variables. In the second case, JavaScript set a value to all the variables but also get the value of three variables (the value of a is not assigned anywhere).

一个简单的代码,它将显示:

A simple code that will show that:

// `this` is the global object if you run this code in the global scope.
// In the browsers the global object is `window`.
Object.defineProperties(this, {  
  "a": {  
    get: function() {
        console.log("get a");
    },
    set: function(value) {
        console.log("set a");
    }
  },  
  "b": {  
    get: function() {
        console.log("get b");
    },
    set: function(value) {
        console.log("set b");
    }
  },  
  "c": {  
    get: function() {
        console.log("get c");
    },
    set: function(value) {
        console.log("set c");
    }
  },  
  "d": {  
    get: function() {
        console.log("get d");
    },
    set: function(value) {
        console.log("set d");
    }
  }  
});

b = c = d = 5;
a = b;

在控制台上你应该有:

set d
set c
set b
get b
set a

正如您所看到的语句 b = c = d = 5 仅JS set 变量,并在 b $ c $上同时调用 set get c>,因为语句 a = b

As you can see for the statement b = c = d = 5 JS only set the variable, and call both set and get on b, because the statement a = b.

这种区别非常重要,因为如果你定义了一些getter对于你的财产而你并不知道这种行为,你最终会使用多个变量赋值出现意外错误。

This distinction is very important, because if you define some getter for your property and you're not aware of this behavior, you will end up with unexpected bug using multiple variable assignments.