【问题标题】:javascript shift() weird recursive with return [duplicate]javascript shift()奇怪的递归返回[重复]
【发布时间】:2020-03-14 21:27:39
【问题描述】:

有人看到下面的带有 shift() 返回的 javascript 递归吗?即使是 3 次 shift() 数组仍然运行 'while 循环'

function combine(nums) {
    while (nums.length) {
        let r = nums.shift();
        console.log(r, ':',  nums);
        combine(nums.slice(0));
  }
}

combine([1,2,3])
---------------  return -----------
    1 : [ 2, 3 ]
    2 : [ 3 ]
    3 : []
    3 : []
    2 : [ 3 ]
    3 : []
    3 : []
------------------------------------

【问题讨论】:

  • 这是正确的,因为安迪标记为重复。我忘记添加 return combine(nums.slice(0));谢谢安迪
  • A return 将避免 while 继续下一次迭代。
  • 我同意 Akshay 的回复

标签: javascript loops recursion while-loop shift


【解决方案1】:

您的示例按预期工作。我稍微修改了一下,可能会更清楚地向您展示它为什么会这样:

另外,你的问题是什么?

function combine(nums, depth) {
  console.log(`Starting depth ${depth} with [${nums}]`);
    while (nums.length) {
      let r = nums.shift();
      let newArr = nums.slice(0);
      console.log(`Removed "${r}". Firing with [${newArr}]`);
      combine(nums.slice(0), depth+1);
      console.log(`Returned to depth ${depth}`);
  }
  console.log(`While end at depth ${depth}`);
}

combine([1,2,3], 0) 

【讨论】:

  • kaczmen 的回答给我留下了深刻的印象。
【解决方案2】:

slice() 方法将数组的一部分浅拷贝返回到新的数组对象中

通过调用combine(nums.slice(0)),您不会对nums 数组执行下一次函数调用,因为slice 将返回新数组。

用途:

function combine(nums) {
    while (nums.length) {
        let r = nums.shift();
        console.log(r, ':',  nums);
        combine(nums);
  }
}

combine([1,2,3]);

【讨论】:

    【解决方案3】:

    我猜你不应该“组合”递归while循环。更重要的是,我认为递归是一种不好的做法。

    function combine(nums) {
        while (nums.length) {
            let r = nums.shift();
            console.log(r, ':',  nums);
            //combine(nums.slice(0)); <- this line is a problem
      }
    }
    
    combine([1,2,3])
    ---------------  return -----------
        1 : [ 2, 3 ]
        2 : [ 3 ]
        3 : []
    ------------------------------------
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-07
      • 1970-01-01
      • 2015-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多