三元运算符在 JS 中无法正常工作

Ternary operator not working properly in JS

我在运行下面的代码中得到了意想不到的结果:

var a = 1, b =2 ,c = 3;
console.log(5*a+ b>0?b:c);
预期结果是:7 但得到 2.

您的代码概念正确,但执行错误。三元组正在正常工作。

目前,您的代码是这样执行的:

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));