由于每种编程语言都不同,而且我对 Javascript 的经验处于基础水平,我想知道如何评估一行中的多个变量赋值
例子:
a = b = c = d = 5;
这样的语句会将 5
分配给 4 个变量 a
、b
、c
和 d
?
谢谢。
最佳答案
简短的回答是是,该语句将分配 5
4 个变量中的每一个 a
, b
, c
和 d
.但是,与所说的相反,不分配 5
至 d
, 然后是 d
的值至 c
, 但它会从右侧开始为每个变量分配相同的值。更清楚地说,你的声明:
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
的值是没有分配到任何地方)。
一个简单的代码将显示:
// `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
和 get
在 b
,因为语句 a = b
.
这个区别非常重要,因为如果你为你的属性定义了一些 getter 而你没有意识到这种行为,你最终会在使用多个变量赋值时遇到意想不到的错误。
关于javascript - 一行中的多个变量赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11514401/