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
Multiply all elements in array
提问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
回答by Sergio
回答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