Assign two variables to the same value with one ex

2019-06-27 09:48发布

问题:

This question already has an answer here:

  • Multiple left-hand assignment with JavaScript 7 answers

Is there any way to assign two variables to the same value?

Just tried this:

let x, y = 'hi'

and it's compiling to this:

'use strict';

var x = void 0,
    y = 'hi';

回答1:

There is absolutely no reason to prefer the destructuring assignment over simply

let x = 'hi', y = x;

Not only it's one statement instead of two, but it also avoids extra allocations (the provided solution with destructuring allocates at least one object with no good reason).



回答2:

Yes, it is possible:

let x, y;
x = y = 'hi';

It is called chaining assignment, making possible to assign a single value to multiple variables.
See more details about assignment operator.


If you have more than 2 variables, it's possible to use the array destructing assignment:

let [w, x, y, z] = Array(4).fill('hi');


回答3:

You can do this way .. But my suggest try to avoid it.

var one, two, three;
one = two = three = "";


回答4:

That's expected behavior. From the EMCA-262 6th edition:

If a LexicalBinding in a let declaration does not have an Initializer the variable is assigned the value undefined when the LexicalBinding is evaluated.



回答5:

var x = y = 'hi';
alert('x'+x);
alert('y'+y);

Fiddle