求反和总和的Array.reduce()的奇怪行为

时间:2019-04-26 09:13:31

标签: javascript reduce

数据:

arr = [0, 0, 0, 1, 1]

代码:

1

!arr[0] + !arr[1] + !arr[2] + !arr[3] + !arr[4]
// 3, correct!

但是...

2

arr.reduce((a, b) => (!a + !b));
// 1, bullshit?!

问题: 为什么 1 。和 2 。不一样?对我没有意义?如何减少()我的数组,使其与 1 中的效果相同。


更新:

arr = [{test: 0}, {test: 0}, {test: 0}, {test: 1}, {test: 1}]

try1 :(为什么不起作用?)

arr.reduce((a, b) => a.test + !b.test, {test: 0});
// NaN

arr.reduce((a, b) => a.test + !b.test, 0);
//NaN

1 个答案:

答案 0 :(得分:2)

您要在每次迭代中取反先前的总和,因此它将被视为1(true)或0(false)。

它的工作方式是:

+-------------+-------------+--------------+-----------------------------+
|  callback   | accumulator | currentValue |        return value         |
+-------------+-------------+--------------+-----------------------------+
| first call  |           0 |            0 | !0 + !0 = true + true = 2   |
| second call |           2 |            0 | !2 + !0 = false + true = 1  |
| third call  |           1 |            1 | !1 + !1 = false + false = 0 |
| fourth call |           0 |            1 | !0 + !1 = true + false = 1  |
+-------------+-------------+--------------+-----------------------------+

因此,请使用Array#reduce方法设置一个初始值,然后否定下一个值并与上一个总和相加。

arr.reduce((a, b) => a + !b, 0);

const arr = [0, 0, 0, 1, 1]

console.log(arr.reduce((a, b) => a + !b, 0));

现在它会像:

+-------------+-------------+--------------+------------------------+
|  callback   | accumulator | currentValue |      return value      |
+-------------+-------------+--------------+------------------------+
| first call  |           0 |            0 | 0 + !0 = 0 + true = 1  |
| second call |           1 |            0 | 1 + !0 = 1 + true = 2  |
| third call  |           2 |            0 | 2 + !0 = 2 + true = 3  |
| fourth call |           3 |            1 | 3 + !1 = 3 + false = 3 |
| fifth call  |           3 |            1 | 3 + !1 = 3 + flase = 3 |
+-------------+-------------+--------------+------------------------+

更新:对于嵌套对象来说,

arr.reduce((a, b) => a + !b.test, 0);