Javascript:使用reduce()方法查找数组中的LCM
我试图在数组中的几个数字中找到LCM(最小公倍数)。为了在数组中的每两个数字之间获得LCM,我使用了无效的Javascript:使用reduce()方法查找数组中的LCM,javascript,Javascript,我试图在数组中的几个数字中找到LCM(最小公倍数)。为了在数组中的每两个数字之间获得LCM,我使用了无效的reduce()方法。请告诉我出了什么问题?谢谢 function gcd(a,b){ //gcd: greatest common divisor //use euclidean algorithm var temp = 0; while(a !== 0){ temp = a; a = b % a; b = temp; } return b
reduce()
方法。请告诉我出了什么问题?谢谢
function gcd(a,b){
//gcd: greatest common divisor
//use euclidean algorithm
var temp = 0;
while(a !== 0){
temp = a;
a = b % a;
b = temp;
}
return b;
}
function lcm(a,b){
//least common multiple between two numbers
return (a * b / gcd(a,b));
}
function smallestCommons(arr) {
//this function is not working, why?
arr.reduce(function(a, b){
return lcm(a, b);
});
}
smallestCommons([1,2,3,4,5]);
//------>undefined
您的
smallestCommons
函数缺少一个return
undefined
是所有没有显式返回的函数的默认返回值
function smallestCommons(arr) {
return arr.reduce(lcm);
}
使用调试器调试代码。您只是忘记了从
smallestCommons
返回。reduce
正在工作。@Bergi,谢谢,我首先想到返回lcm(a,b)
将返回结果。@ZacharyWang:这是从您传递给reduce
的回调函数中返回的,而不是从smallestCommons
函数中返回的。@Bergi非常感谢,现在我真的得到了它!谢谢,我首先想到的是返回lcm(a,b);我会把结果还给我。