Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/476.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript:使用reduce()方法查找数组中的LCM_Javascript - Fatal编程技术网

Javascript:使用reduce()方法查找数组中的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

我试图在数组中的几个数字中找到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;
}

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);我会把结果还给我。