该函数如何检索变量“I”? [英] How does this function retreive the variable "I"?

查看:69
本文介绍了该函数如何检索变量“I”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var funcs = [];
    
for (let i = 0; i < 10; i++) {
    funcs.push(function() { console.log(i); });
}
    
funcs.forEach(function(func) {
    func();   //How does this function retreive the variable "i"?
});





func()如何;函数retreive变量i?



我尝试过:



当运行func()时,代码是否返回到创建函数的第4行?

或者用console.log(一个数字)替换func()? />
或者func()字面上替换为console.log(i)?



How does the func(); function retreive the variable "i"?

What I have tried:

When func() is run, does the code return to line 4, where the function was created?
Or is func() replaced with "console.log(a number)"?
Or is func() literally replaced with "console.log(i)"?

推荐答案

引用:

func()如何;函数retreive变量i?

How does the func(); function retreive the variable "i"?



使用return语句,它向调用者返回一个值:


With the "return" statement, which returns a value to the caller:

var funcs = [];
    
for (let i = 0; i < 10; i++) {
    funcs.push(function() { return i; });
}
    
funcs.forEach(function(func) {
    var i = func(); // note: you do not have to call it "i", you can give this variable any valid name
    console.log(i);
});




Quote:

当运行func()时,代码是否返回第4行,其中函数是创建?

或者是func()字面上替换为console.log(一个数字)?

When func() is run, does the code return to line 4, where the function was created?
Or is func() literally replaced with "console.log(a number)"?



你实际上并没有返回到第4行:当你打电话给 funcs.push(...)时,你创建一个返回值的新函数,该值是 i 的值。因此,一旦你离开 for 循环,你的数组就包含10个函数定义:一个返回 0 的函数,返回 1 的函数,依此类推。 .forEach 逐个迭代所有这些函数。



在你的评论中,你问为什么它会如果您使用 var 而不是let,则始终打印10。原因是范围 [ ^ ]: let 具有块范围, var 具有函数作用域(或者在函数外部定义,如此处,全局作用域)。因此,当您使用 var 时, i 将始终为相同的i,因为它具有相同的范围, let 不会发生,因为它有不同的范围。


You don't actually "return" to line 4: when you call funcs.push(...), you create a new function that returns a value, and that value is what i is. So, once you are out of your for loops, your array contains 10 function definitions: a function that returns 0, a function that returns 1 and so on. The .forEach iterates over all these functions one by one.

In your comment, you asked why it would always print "10" if you used var instead of let. The reason is scope[^] : let has block scope, var has function scope (or when defined outside a function, like here, global scope). So when you use var, then i will always be "the same i" because it has the same scope, which does not happen with let, because it has a different scope.


这篇关于该函数如何检索变量“I”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆