我正在试图找出一个问题,我需要找到数组中所有数字的乘积。
对于我的生活,我无法弄清楚为什么这会一直未定义。
我很想知道为什么我的代码无效的任何建议。谢谢!
function mutliplyAllElements(arr) {
arr.reduce(function(x, y) {
return x * y;
});
}
mutliplyAllElements([2, 3, 100]); // 600
答案 0 :(得分:1)
You are getting undefined because function mutliplyAllElements
does not return anything. You have to return
the value in the function.
function mutliplyAllElements(arr) {
let val = arr.reduce(function(x, y) {
return x * y;
});
return val;
}
console.log(mutliplyAllElements([2, 3, 100]));
Or you can make it shorter as:
function mutliplyAllElements(arr) {
return arr.reduce((x, y) => x * y);
}
console.log( mutliplyAllElements([2, 3, 100]) );