Check exactly one boolean option set

后端 未结 6 587
后悔当初
后悔当初 2021-01-17 18:21

Well, this is kind of hacky:

function b2n(boo) {
    return boo ? 1 : 0;
}

if(b2n(opt1) + b2n(opt2) + b2n(opt3) !== 1) {
    throw new Error(\"Exactly one o         


        
6条回答
  •  萌比男神i
    2021-01-17 19:12

    You can do this :

    if ( !!opt1 + !!opt2 + !!opt3 !== 1 ) {
    

    It works because

    • !! makes a boolean from any value (true if the objects evaluates as true in if(value))
    • when adding booleans you get 1 for true and 0 for false.

提交回复
热议问题