Javascript - Ternary Operator with Multiple Statements

后端 未结 5 1907
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条回答
  •  眼角桃花
    2020-11-29 22:39

    Expanding on this topic with ES6 code example. If you're using one side of the TRUE : FALSE argument to iterate thru all cases in one IF, it makes sense to separate the code as if it's a switch | case statement.

    Nesting implies that there is branching logic, while it is logically nested, writing nested IF's complicates what we're doing in my example. Like a lawyer over explaining a problem to a jury. IMO, you want to explain the point in it's simplest form. For instance, I find this example the most logical way of expressing nested ifs where the TRUE is executed. The final false is your last else {} choreDoor is either 0,1 or 2:

    choreDoor === 0 ? 
       (openDoor1 = botDoorPath,
        openDoor2 = beachDoorPath,
        openDoor3 = spaceDoorPath)
    : choreDoor === 1 ? 
       (openDoor2 = botDoorPath,
        openDoor1 = beachDoorPath, 
        openDoor3 = spaceDoorPath) 
    : choreDoor === 2 ?
       (openDoor3 = botDoorPath,
        openDoor1 = beachDoorPath, 
        openDoor2 = spaceDoorPath)
    : false;
    

提交回复
热议问题