javascript shift() 奇怪的递归与返回

标签 javascript loops recursion while-loop shift

有人看到下面带有shift()返回的javascript递归吗?即使三次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 : []
------------------------------------

最佳答案

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

另外,你有什么问题吗?

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) 

关于javascript shift() 奇怪的递归与返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58932716/

相关文章:

javascript - 根据鼠标移入/移出显示/隐藏 D3 元素

javascript - 更改图像 onLoad() - 我的失败在哪里?

javascript - 创建网络 map 应用程序。 Leaflet 还是 OpenLayers?

JavaScript:数字等级到字母等级

python - 如何从Python中的特定点开始Itertools循环?

javascript - 单击表单中的按钮会导致页面刷新

ruby - 使用 Mechanize 点击谷歌页面

c - 尾递归究竟是如何工作的?

java - 递归时的字符串参数

java - 优化递归回溯