JavaScript中与三元操作员的短路互动
我目前正在学习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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论