[英]why value of i is showing undefined when output of the below code is obtained
let i = 0; const g = (i, callback) => { if (i < 100) { callback(i) i++; g(i, callback) } else return } const k = (i) => { setTimeout((i) => { console.log('hi' + i); }, i * 1000); } g(i, k);
This is the code which uses callback to print hi concatenated by the value of i at an interval of 1 second for 100 times.这是使用回调以 1 秒的间隔打印 hi 由 i 的值连接 100 次的代码。 i am not able to identify where it is going wrong .It will be very greatful if anyone could help me with this.
我无法确定哪里出了问题。如果有人能帮我解决这个问题,那就太好了。
The i
inside the function passed to setTimeout
shadows the one k
accepts as argument.传递给
setTimeout
的函数中的i
setTimeout
了k
接受的参数。 So to correct a snippet you just need to remove callback's argument:所以要更正一个片段,你只需要删除回调的参数:
let i = 0; const g = (i, callback) => { if (i < 100) { callback(i) i++; g(i, callback) } else return } const k = (i) => { setTimeout(() => { // <------ I removed `i` here console.log('hi' + i); }, i * 1000); } g(i, k);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.