这个递归函数为什么会输出一个包含 x 的数组,重复 n 次?

huangapple go评论75阅读模式
英文:

Why does this recursive function output an array of x, n number of times?

问题

这个递归函数为什么有效?

let arr = []

function rep(x, n) {
  if (Math.sign(x) === -1) {
    return []
  }

  if (x < 1) {
    return 1
  } else {
    rep(x - 1, n)
  }
  arr.push(n)
  return arr
}

console.log(rep(5, 5))

我正在学习JavaScript和递归函数。我创建了上面的函数,以在数组中输出x,n次数。例如,rep(2,5)将输出[5,5],rep(3,3)将输出[3,3,3]等。但我不完全理解它为什么有效。

我是否正确地认为这个函数最后执行的是返回完成的数组?如果是这样,为什么当x变为-1时它不返回[]或1?我认为我搞混了,但我会感激一个清晰的解释。谢谢。

英文:

Why does this recursive function work?

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let arr = []

function rep(x, n) {
  if (Math.sign(x) === -1) {
    return []
  }

  if (x &lt; 1) {
    return 1
  } else {
    rep(x - 1, n)
  }
  arr.push(n)
  return arr
}

console.log(rep(5, 5))

<!-- end snippet -->

I'm learning JS and about recursive functions. I made the above function to output an array of x, n number of times in an array. E.g. rep(2,5) would output [5,5], rep (3,3) would output [3,3,3] etc. But I don't fully understand why it works.

Am I right in thinking that the last thing the function does is return the completed array? If so, why does it not return [] or 1 when x goes to -1? I think I'm confusing myself but I'd appreciate an clear explanation. Thanks

I created the above function and was not expecting it work. So, I made it but I don't fully understand why it works.

答案1

得分: 1

如果是这样,为什么当 x 变为 -1 时它不返回 [] 或 1 呢?

它会的。但考虑一下它将返回到哪里,以及代码的下一步会对其做什么。

你只在 console.log(rep(5, 5)) 处记录了。

你没有在 x-1 的任何时候记录响应。

你可能会受益于使用调试器逐步执行代码

英文:

> If so, why does it not return [] or 1 when x goes to -1?

It does. But think about where it returns that to and what that bit of code does with it next.

You only ever log console.log(rep(5, 5)).

You don't log the response at any point where x is -1.

You would probably benefit from stepping through the code with a debugger.

答案2

得分: 1

当调用 rep(5,5) 时,递归调用如下:

rep(5,5)
	rep(4,5)
		rep(3,5)
			rep(2,5)
				rep(1,5)

当 x = 1 时,满足下面的条件会导致递归停止。因此,

  if (x &lt; 1) {
    return 1
  }

所以,由于 Math.sign(x) 永远不等于 -1,下面的代码不会执行:

if (Math.sign(x) === -1) {
    return []
}

然而,如果你运行 rep(-3, 5),则满足上述条件,输出将为 []

英文:

When you call rep(5,5), it gets called recursively as below:

rep(5,5)
	rep(4,5)
		rep(3,5)
			rep(2,5)
				rep(1,5)

When x = 1, the below condition is satisfied and causes the recursion to stop. So,

  if (x &lt; 1) {
    return 1
  }

So, the below code does not get executed as Math.sign(x) never equal to -1

if (Math.sign(x) === -1) {
    return []
}

However, if you run call rep(-3, 5), the above condition is satisfied and you will get [] as the output.

huangapple
  • 本文由 发表于 2023年5月22日 07:03:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/76302264.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定