Assign two variables to the same value with one expression?

This question already has an answer here:

  • Multiple left-hand assignment with JavaScript 6 answers

  • 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).


    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');
    

    你可以这样做..但我的建议尽量避免它。

    var one, two, three;
    one = two = three = "";
    
    链接地址: http://www.djcxy.com/p/69972.html

    上一篇: Javascript中多重变量赋值的正确方法

    下一篇: 用一个表达式将两个变量赋值为相同的值?