Reduce error report Reduce of empty array with no initial value processing method

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

1. Provide an initial value as the neutral element of the operator, such as 0 in addition, 1 in multiplication, or an empty string in merge.

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. Judge the length of the array first, and then call the reduce method if the length is not 0;

Guess you like

Origin blog.csdn.net/taozi550185271/article/details/106217956