三元运算符和&&运算符之间的确切区别是什么?

时间:2019-02-15 16:40:10

标签: javascript

我只是在玩一个代码,在将三元运算符转换为&&||运算符的同时,我的代码发现了一个神秘的行为:

let  a = 3;
a = a > 1 && 2 || a;
console.log(a);

let b = 3;
b = b > 1 ? 2 : b;
console.log(b);

// a and b both are same. It's fine.

const getAdjacentHighestProduct = (arr) => {
  let max = -Infinity;
  arr.reduce((a, c) => {
    let product = a * c;
    max = product > max ? product : max;
    return a = c;
  });
  return max;
};

const aProduct = getAdjacentHighestProduct([1, 0, 1, 0, 1000]);
console.log(aProduct);

const getAdjacentHighestProduct2 = (arr) => {
  let max = -Infinity;
  arr.reduce((a, c) => {
    let product = a * c;
    max = product > max && product || max;
    return a = c;
  });
  return max;
};

const aProduct2 = getAdjacentHighestProduct2([1, 0, 1, 0, 1000]);
console.log(aProduct2);

// aProduct, aProduct2 are not the same. It's not okay.

此外,在这里我可以看到aProduct2的结果为-Infinity。但是在测试用例中尝试相同的代码时,我看到的结果是null,也许是适当的环境(浏览器与node.js)。

因此,我很好奇为什么两个结果都不相同,为什么返回-Infinitynull而不是0

那么,使用三元运算符和&& ||运算符到底有什么区别?

这是测试结果的屏幕截图:

enter image description here

3 个答案:

答案 0 :(得分:4)

如果b虚假,则true ? b : c将是b,而true && b || c将是c

function ternary(a, b, c) {
  return a ? b : c;
}
function andOr(a, b, c) {
  return a && b || c;
}

console.log(ternary(1, 0, 3), andOr(1, 0, 3));

答案 1 :(得分:1)

谢谢大家!我得到了答案。让我们在这里打破它们:

(希望您能理解,不希望给出解释)

0 > -Infinity && 0 || -Infinity
false > -Infinity && false || -Infinity
false > -Infinity

null的值是我好奇的关键。啊,我刚刚找到了right answer

var a = {b: Infinity, c: 10};
console.log(JSON.stringify(a));

所以,我认为他们使用JSON.stringify来满足测试结果。

答案 2 :(得分:-2)

区别是:他们做不同的事情。 ;)

三元运算符

x = c ? a : b

if c then
  x = a;
else
  x = b;
end if

逻辑与

x = a && b

逻辑或

x = a || b
相关问题