Multiply all elements in array

前端 未结 7 462
不思量自难忘°
不思量自难忘° 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:34

    The cause is already known. Here's an alternative - using Array.reduce for your method:

    console.log( [1, 2, 3].reduce( (a, b) => a * b ) );
    console.log( Array.from( {length: 20} )
      .map( (v, i) => i + 1 )
      .reduce( (a,b) => a * b )
      .toLocaleString());
    
    // for empty arrays, use some initial value
    const arr = [];
    if (arr.reduce( (a, b) => a * b, -1 ) === -1) {
      console.error(`The given array ${arr} is empty`);
    }

    See also

提交回复
热议问题