数组应该在递归函数内部

时间:2015-02-17 07:38:16

标签: javascript arrays function recursion

代码是用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)) 

3 个答案:

答案 0 :(得分:0)

喜欢这样

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

答案 1 :(得分:0)

喜欢

 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

答案 2 :(得分:0)

在因子函数中声明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;
    }