search

Home  >  Q&A  >  body text

javascript - Will parameters change when calling recursively in js

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_u1582phpcn_u15822790 days ago635

reply all(2)I'll reply

  • 世界只因有你

    世界只因有你2017-05-19 10:43:24

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

    reply
    0
  • 过去多啦不再A梦

    过去多啦不再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);

    reply
    0
  • Cancelreply