JavaScript中与三元操作员的短路互动

发布于 2025-01-22 13:07:48 字数 1094 浏览 0 评论 0原文

我目前正在学习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'}]
);

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

I'm currently learning JavaScript and I encountered this problem:

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'}]
);

When you run each of the above code, you'll notice that the first one only modifies the "odd" property which is not what I'm expecting when I used the && operator but when I changed it to the || operator I got the code that I was expecting originally. Can someone explain to me how I got those 2 outputs?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文