javascript 将数组中的所有元素相乘

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19175063/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 14:39:48  来源:igfitidea点击:

Multiply all elements in array

javascript

提问by Joh Smith

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've got this code, but it returns undefined.

我在这里找不到我真正要找的例子。我想将所有数组元素相乘,因此如果数组包含 [1,2,3],则总和将为 1*2*3=6;到目前为止,我已经得到了这段代码,但它返回未定义。

function multiply (array) {
    var sum=1;
    for (var i=0; i<array.length; i++) {
        sum = sum * array[i];
    } 
    return sum;
}
console.log(multiply[1,2,3]);

Could anyone please explain, what am I missing here? Thanks in advance!

谁能解释一下,我在这里错过了什么?提前致谢!

回答by KooiInc

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

原因已经知道了。这是一种替代方法 -Array.reduce用于您的方法:

[1, 2, 3].reduce( (a,b) => a * b, 0 ); //=> 6

See also

也可以看看

回答by Sergio

You need to have ()when you call the function.

()调用函数时需要有。

Like multiply([1,2,3])

喜欢 multiply([1,2,3])

Demo here

演示在这里

回答by Denis

You're not calling multiply as a function:

您不是将乘法作为函数调用:

multiply([1,2,3]);

回答by Ritambhar Das

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)

如果你想乘一些连续的数字,比如 1,2,3 那么,然后应用此代码并在控制台中输入数字(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