[英]Why my JavaScript function won't end?
So I have the following code, from which I expect the x
function to return null
after being called 3
times but it keeps returning the the same function: 因此,我有以下代码,我希望x
函数在被调用3
次后会返回null
,但它始终返回相同的函数:
const repeat = (n, tailFn) => {
for (let i = 0; i < n; i++) {
tailFn = () => tailFn;
}
return tailFn;
};
const x = repeat(2, x => null);
console.log(x()); // function tailFn() { return _tailFn }
console.log(x()()); // function tailFn() { return _tailFn }
console.log(x()()()()()()); // function tailFn() { return _tailFn }
What am I doing wrong? 我究竟做错了什么? See it on CodePen . 在CodePen上看到它。
Your function just assigns () => tailFn
to tailFn
three times and then returns it. 您的函数只需将() => tailFn
分配给tailFn
三次,然后返回它。 Instead, you should return a function which returns repeat(n - 1, tailFn)
if n
is not 0
, and tailFn
otherwise. 相反,您应该返回一个函数,如果n
不为0
,则该函数返回repeat(n - 1, tailFn)
,否则tailFn
。
const repeat = (n, tailFn) => { return n !== 0 ? () => repeat(n - 1, tailFn) : tailFn; }; const x = repeat(2, x => null); console.log(x()); // () => repeat(n - 1, tailFn) console.log(x()()); // x => null console.log(x()()()); // null
You have created a function that ALWAYS returns itself, 您创建了一个始终返回自身的函数,
tailFn=()=>tailFn;
actually the loop is meaningless.Its behavior is similar to a recursive function without a base case. 实际上,循环是没有意义的,它的行为类似于没有基本情况的递归函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.