Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
201 views
in Technique[技术] by (71.8m points)

javascript - Multiple variable assignments in one row

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

Example:

 a = b = c = d = 5;

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

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;

It's equivalent to:

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

Not to:

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

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;

On the console you should have:

set d
set c
set b
get b
set a

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...