结合三元与和或javascript?

为什么会这样呢?

let number = 5
const result = number == 4 ? 'true 1' : 'false 1' || number == 3 ? 'true 2' : 'false 2'  || number == 5 ? 'true 3' : 'false 3'
console.log(result)

//返回结果为true 2 回答true 2为什么会这样?

评论
  • Young
    Young 回复

    您的陈述

    const result = number == 4 ? 'true 1' : 'false 1' || number == 3 ? 'true 2' : 'false 2'  || number == 5 ? 'true 3' : 'false 3'
    

    被解释为好像被写

    const result = (number == 4) ? 'true 1' : ('false 1' || number == 3) ? 'true 2' : ('false 2 || number == 5) ? 'true 3' : 'false 3';
    

    In particular, this part ('false 1' || number ==3) is true because 'false 1' is a non-empty string.

    I am not sure what you were attempting, but note that ? : ultimately can have just one value: either the value of the first expression, or the value of the second. Thus those 'false n' strings really don't make any sense: either one of those conditional tests of number will be true, or none will be.