Multiply all elements in array

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

    If you want to multiply some consecutive numbers like 1,2,3 then, then apply this code and enter the number in the console (arr)

    let array = [];
    
    function factorisation(arr) {
        for (let j = arr; j > 0; j--) {
            array.push(j);
        }
        return multiply();
    }
    
    function multiply() {
        var sum = 1;
        for (var i = 0; i < array.length; i++) {
            sum = sum * array[i];
        }
        return sum;
    }
    
    console.log(factorisation(5));
    //5*4*3*2*1 = 120
    

提交回复
热议问题