javascript shift() 奇怪的递归 return
javascript shift() weird recursive with return
有人看到下面的 javascript 递归与 shift() return 吗?即使三次 shift() 数组仍然 运行 'while loop'
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 : []
------------------------------------
我想你不应该 "combine" 递归 和 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 : []
------------------------------------
您的示例按预期工作。我稍微修改了它,以便更清楚地向您展示为什么它会这样:
另外,你的问题是什么?
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)
The slice() method returns a shallow copy of a portion of an array into a new array object
通过调用 combine(nums.slice(0))
,您不会对 nums
数组执行下一个函数调用,因为 slice
将 return 新数组。
使用:
function combine(nums) {
while (nums.length) {
let r = nums.shift();
console.log(r, ':', nums);
combine(nums);
}
}
combine([1,2,3]);
有人看到下面的 javascript 递归与 shift() return 吗?即使三次 shift() 数组仍然 运行 'while loop'
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 : []
------------------------------------
我想你不应该 "combine" 递归 和 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 : []
------------------------------------
您的示例按预期工作。我稍微修改了它,以便更清楚地向您展示为什么它会这样:
另外,你的问题是什么?
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)
The slice() method returns a shallow copy of a portion of an array into a new array object
通过调用 combine(nums.slice(0))
,您不会对 nums
数组执行下一个函数调用,因为 slice
将 return 新数组。
使用:
function combine(nums) {
while (nums.length) {
let r = nums.shift();
console.log(r, ':', nums);
combine(nums);
}
}
combine([1,2,3]);