Multiply all elements in array

前端 未结 7 458
不思量自难忘°
不思量自难忘° 2020-12-05 10:16

I couldn\'t find an example here what I\'m really looking for. I\'d like to multiply all array elements, so if an array contains [1,2,3] the sum would be 1*2*3=6; So far I\'

7条回答
  •  不思量自难忘°
    2020-12-05 10:30

    The reduce() method executes a provided function for each value of the array and reduces the array to a single value

        const arr = [1,2,3];
        const sum = arr.reduce((prevValue,curValue) => {
            return prevValue * curValue
        },1);
        console.log(sum);

    prevValue is the initial value and it's equal 1 in this example

    curValue is the value of the current element in array

提交回复
热议问题