代码之家  ›  专栏  ›  技术社区  ›  Eric

内联比较分配多个变量

  •  0
  • Eric  · 技术社区  · 3 年前

    在JavaScript中,在比较内联(inline)时是否可以为多个变量赋值?操作员)?

    下面是一个我希望可以工作的非工作代码的简化版本

     var toto = true;
     var test0, test1;
    
     toto ? test0 = 'test0', test1 = 'test1' : null;
    
    1 回复  |  直到 3 年前
        1
  •  2
  •   Quentin    3 年前

    永远不要尝试将条件运算符用作 if 声明。它被设计成输出一个值。

    something = condition ? value : other_value
    

    destructuring assignment 在一次操作中分配多个值。

    var toto = true;
    var test0, test1;
    
    [test0, test1] = toto ? ['test0', 'test1'] : [null, null];
    console.log({ test0, test1 });
    
    toto = false;
    [test0, test1] = toto ? ['test0', 'test1'] : [null, null];
    console.log({ test0, test1 });