JavaScript 中与三元运算符的短路交互

Short-Circuiting Interaction with Ternary Operator in JavaScript

提问人:ColstonBod-oy 提问时间:4/20/2022 更新时间:4/20/2022 访问量:47

问:

我目前正在学习JavaScript,我遇到了这个问题:

const numArray = [1, 6, 9, 4, 21, 8, 15];

const sumEvenOdd = numArray.reduce((acc, current) => 
   console.log(acc) && current % 2 === 0 
      ? acc.map(i => i.hasOwnProperty('even') ? {...i, even: i.even + current} : i)
      : acc.map(i => i.hasOwnProperty('odd') ? {...i, odd: i.odd + current} : i), 
      [{"even": 0, color: 'red'}, {"odd": 0, color: 'green'}]
);
const numArray = [1, 6, 9, 4, 21, 8, 15];

const sumEvenOdd = numArray.reduce((acc, current) => 
   console.log(acc) || current % 2 === 0 
      ? acc.map(i => i.hasOwnProperty('even') ? {...i, even: i.even + current} : i)
      : acc.map(i => i.hasOwnProperty('odd') ? {...i, odd: i.odd + current} : i), 
      [{"even": 0, color: 'red'}, {"odd": 0, color: 'green'}]
);

当您运行上述每个代码时,您会注意到第一个代码仅修改“odd”属性,这不是我在使用 && 运算符时所期望的,但是当我将其更改为 || 运算符时,我得到了我最初期望的代码。有人可以向我解释我是如何获得这 2 个输出的吗?

JavaScript 算法 条件运算符 短路

评论

3赞 Tobias S. 4/20/2022
为什么要使用 OR REDUCE 函数? 始终返回 undefined,即 false。为什么要将其包含在布尔运算中?&&||console.log
1赞 Ivar 4/20/2022
我强烈建议在箭头函数中使用块()。这样,您可以拥有多个语句并使用简单的 if-else 构造。它将大大提高可读性并降低出现您现在遇到的错误的机会。{ ... }
2赞 epascarello 4/20/2022
console.log 不返回任何内容......所以它永远不会是真实的。所以失败了。&&
1赞 Yannick K 4/20/2022
console.log()返回 ,所以基本上你最终会得到:undefined(false && <true/false>) ? <map even numbers> : <map odd numbers>
1赞 Ivar 4/20/2022
@ColstonBod-oy 使用这样的东西。

答: 暂无答案