一行中的多个变量赋值 [英] Multiple variable assignments in one row

查看:171
本文介绍了一行中的多个变量赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于每种编程语言都不同,我对Javascript的体验是基本的,我想知道,如何评估一行中的多个变量赋值

As each programming language is different and my experience with Javascript is on basic level, I would like to know, how multiple variable assignments in one row are evaluated

示例:

 a = b = c = d = 5;

这样的陈述是否会为每个人分配 5 4个变量 a b c d

Will such statement assign 5 to each of 4 variables a, b, c and d?

谢谢。

推荐答案

简短的回答是,该语句将 5 分配给4个变量中的每一个 a b c d 。但是,与上述内容相反,不会将 5 分配给 d ,然后是<$ c的值$ c> 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 设置所有变量的值获取三个变量的值(<$ c $的值) c> 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 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.

这篇关于一行中的多个变量赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆