简体   繁体   English

为什么在获得以下代码的输出时 i 的值显示为 undefined

[英]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 setTimeoutk接受的参数。 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.

相关问题 尝试在下面的代码中访问db.collection时,为什么会得到未定义的信息? - Why am I getting an undefined when I try to access db.collection in the code below? 使用jQuery获取元素时,值未定义 - Value is undefined when element is obtained with jQuery 遇到以下代码未定义输出的问题 - Having trouble with undefined output from this code below 当我使用 document.write 函数打印下面代码中的数字时,它会在每个输出的右侧插入 0。为什么会这样? - When I use the document.write function to print the number in code below then it insert the 0 on right side of each output.Why it is happening? 为什么用cheerio运行这段代码没有output? - Why is there no output when I run this code with cheerio? 为什么 output 中没有显示范围值? - Why is it not showing range value in output? 我无法获得以下代码的输出 - I am unable to get the output for the code below 为什么当 AST 已经知道该值时此代码返回 undefined - Why this code returns undefined when AST already knows the value 我在尝试访问 function 参数时遇到错误“数据”未定义,如以下代码的注释中所述 - I am facing an error 'data' is undefined when trying to access the function parameter as mentioned in the comment in below code 为什么这段代码显示未定义和类型错误? - Why this code is showing me undefined and type error?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM