reduce报错Reduce of empty array with no initial value处理方法

报错情况:Uncaught TypeError: Reduce of empty array with no initial value
    at Array.reduce (<anonymous>)
    at myFunction (<anonymous>:8:57)

1、提供一个初始值作为操作符的中立元素,比如加法里的0,乘法里的1,或者是合并中的一个空字符串。

var ints = [0, -1, -2, -3, -4, -5];
ints.filter(x => x < 0)         // removes all elements
    .reduce((x, y) => x + y, 0) // the initial value is the neutral element of the addition

2、先行判断array的长度,长度不为0再调用reduce方法;

猜你喜欢

转载自blog.csdn.net/taozi550185271/article/details/106217956