Multiply all elements in array

前端 未结 7 461
不思量自难忘°
不思量自难忘° 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条回答
  •  萌比男神i
    2020-12-05 10:45

    The alternative way to use Array.reduce should have the initial value set to 1 or else our function will return 0 no matter what.

    [1, 2, 3].reduce((a, b)=> a*b, 1)
    

    per https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

提交回复
热议问题