我正在运行以下代码并得到意外的结果:
var a = 1, b =2 ,c = 3;
console.log(5*a+ b>0?b:c);
答案 0 :(得分:5)
您的代码概念正确,但是执行错误。三元正在正确地工作。
此刻,您的代码正在这样执行:
const a = 1
const b = 2
const c = 3
// This will evaluate to true, since 5 * 1 + 2 = 7, and 7 is greater than 0
if (5 * a + b > 0) {
// So return b
console.log(b)
} else {
console.log(c)
}
您应该使用方括号分隔三元:
const a = 1
const b = 2
const c = 3
console.log(5 * a + (b > 0 ? b : c));