Javascript - Ternary Operator with Multiple Statements

后端 未结 5 1915
Happy的楠姐
Happy的楠姐 2020-11-29 22:29

Is this valid JavaScript? I saw an example where someone used commas in the ternary operator conditions, and it was marked as an error in my editor, and the example didn\'t

5条回答
  •  猫巷女王i
    2020-11-29 22:49

    Yes:

    a=1;
    b=2;
    
    a!==b ? (a=1, b=2) : (a=2, b=1)
    
    console.log(a);     // 1
    console.log(b);     // 2
    

    and:

    a=1;
    b=2;
    
    a===b ? (a=1, b=2) : (a=2, b=1)
    
    console.log(a);     // 2
    console.log(b);     // 1
    

    As you can analyze, changing the equality operator reacts correctly to our test if you look at the results.

提交回复
热议问题