javascript - Will parameters change when calling recursively in js
phpcn_u1582
phpcn_u1582 2017-05-19 10:41:24
0
2
639

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]  ...
phpcn_u1582
phpcn_u1582

reply all(2)
世界只因有你

Because args.concat returns a new array and will not affect the original array.

过去多啦不再A梦
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);
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template