A recursive function as shown below, why does args.concat(i)
not increase according to the loop? args is a reference type. In my mind, this args will put 0-9 in it during the loop.
var loop = (fn, n, args = []) => {
if (n === 0) {
return fn.apply(fn, args);
}
for (var i = 0; i <= 9; i++) {
loop(fn, n - 1, args.concat(i)); // 这里的args.concat(i),在递归的每个栈都是“新”的
}
}
loop((...a) => console.log(a), 2);
//结果: [0,0] [0,1] ...
世界只因有你2017-05-19 10:43:24
Because args.concat returns a new array and will not affect the original array.
过去多啦不再A梦2017-05-19 10:43:24
var loop = (fn, n, args = []) => {
if (n === 0) {
return fn.apply(fn, args);
}
for (var i = 0; i <= 9; i++) {
loop(fn, n - 1, args=args.concat(i)); // 这里的args.concat(i),在递归的每个栈都是“新”的
}
}
loop((...a) => console.log(a), 2);