有人看到下面带有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/