Javascript && 和 ||运算符和在线三元函数产生疯狂的结果

Javascript && and || operators and in line ternary functions produces INSANE results

var str = '1' || '2'

console.log(str) 输出 1 好吧……有道理。 1 在“||”之前,因此“||”之后的内容无关紧要

var str = '1' || (true) ? '2' : '3'

console.log(str) 输出 2 ...什么?!这永远不应该发生。 “1”在“||”前面

var str = '1' || (false) ? '2' : '3'

console.log(str) 输出 2 ...好吧,JS回家你显然喝醉了。

console.log('1' || (true) ? '2' : '3');
//is interpreted as 
console.log(('1' || true) ? '2' : '3');
//you mean to write
console.log('1' || (true ? '2' : '3'));

你期待的是

'1' || ((true) ? '2' : '3')

,但基本上你所做的是

('1' || (true)) ? '2' : '3'

您正在为 if 语句创建 shorthand,其中左边的部分被求值,然后返回正确的值,因此 '1' 求值为真,这样您得到 '2' 作为结果