Javascript递归函数

mengerJavascript
这篇文章约4分阅读完。

记录学习Javascript递归过程中的问题和解决方案

基本的JavaScript:使用递归创建倒计时

------------------基本的JavaScript:使用递归创建倒计时-----------------------
Solutions
Solution 0 (Click to Show/Hide)
function countdown(n){
  if(n < 1){
    return [];
  }else{
    const xx = countdown(n - 1);
    xx.unshift(n)
    return xx;
  }
}

Solution 1 (Click to Show/Hide)
function countdown(n) {
  if (n < 1) {
    return [];
  } else {
    const arr = countdown(n - 1);
    arr.unshift(n);
    return arr;
  }
}

Solution 2 (Click to Show/Hide)
function countdown(n) {
  if (n < 1) {
    return [];
  } else {
    const arr = countdown(n - 1);
    arr.splice(0, 0, n);
    return arr;
  }
}

Solution 3 (Click to Show/Hide)
function countdown(n){
   return n < 1 ? [] : [n].concat(countdown(n - 1));
}

Solution 4 (Click to Show/Hide)
function countdown(n){
   return n < 1 ? [] : [n, ...countdown(n - 1)];
}

基本的JavaScript:使用递归创建数字范围

------------------基本的JavaScript:使用递归创建数字范围-----------------------
Solutions
Solution 0 (Click to Show/Hide)
function rangeOfNumbers(startNum, endNum) {
  if(startNum - endNum === 0){
    return [startNum];
  }else{
    var xx = rangeOfNumbers(startNum, endNum - 1);//1相同名称函数错误
    xx.push(endNum);//2自减值传错
    return xx;
  }
}

Solution 1 (Click to Show/Hide)
function rangeOfNumbers(startNum, endNum) {
  if (endNum - startNum === 0) {
    return [startNum];
  } else {
    var numbers = rangeOfNumbers(startNum, endNum - 1);
    numbers.push(endNum);
    return numbers;
  }
}

Solution 2 (Click to Show/Hide)
function rangeOfNumbers(startNum, endNum) {
  return startNum === endNum
    ? [startNum]
    : rangeOfNumbers(startNum, endNum - 1).concat(endNum);
}

Solution 3 (Click to Show/Hide)
function rangeOfNumbers(startNum, endNum) {
  return startNum === endNum
    ? [startNum]
    : [...rangeOfNumbers(startNum, endNum - 1), endNum ];
}

评论

复制标题和 URL