数组应该在递归函数中

array should be inside recursive function

代码在JavaScript中。我的问题是如何在函数内创建 arr 数组。我不希望它在函数之外。上面的代码在函数之外显示了 arr 数组,我不喜欢这样。你可以提出任何建议,因为我的目标是找到数字 36 的所有阶乘。答案应该是这样的数组 [36,18,12,9,6,4,3,2,1].

var arr= []
function factor(number, divisor) {
    if(divisor >= 1) { 
        if(number % divisor == 0) {
            arr.push(divisor)
            return factor(number, divisor - 1)
        } else {
            return factor(number, divisor - 1);
        }
    }
    return arr;
}

console.log("")
console.log("factor of a number 36")
console.log(factor(36,36)) 

像这样

function factor(number, divisor, arr) {
  arr = arr || [];

  if (divisor >= 1) {
    if (number % divisor === 0) {
      arr.push(divisor);
      return factor(number, divisor - 1, arr);
    } else {
      return factor(number, divisor - 1, arr);
    }
  }

  return arr;
}

Example

或者你可以这样做,只传递两个参数

function factor(number, divisor) {
  return function _factor(number, divisor, arr) {
    arr = arr || [];

    if (divisor >= 1) {
      if (number % divisor === 0) {
        arr.push(divisor);
        return _factor(number, divisor - 1, arr);
      } else {
        return _factor(number, divisor - 1, arr);
      }
    }

    return arr;
  }(number, divisor);
}

Example

喜欢

 function factor(number, divisor, s)
  {
  if(number==divisor) arr = [];
  if(divisor >= 1)
  { 
  if(number % divisor == 0)
  {
    arr.push(divisor)
    return factor(number, divisor - 1)
  }
  else
  {
     return factor(number, divisor - 1);
  }
   }
  return arr;
 }

工作Fiddle

在 factor 函数中声明 arr :

function factor(number, divisor, s) {
        var arr = []
        if (divisor >= 1) {
            if (number % divisor == 0) {
                arr.push(divisor)
                return factor(number, divisor - 1)
            } else {
                return factor(number, divisor - 1);
            }
        }
        return arr;
    }