循环和闭包。 For和Var [英] Loops and closures. For and Var

查看:82
本文介绍了循环和闭包。 For和Var的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找到了许多主题来解释此问题,这些主题涉及如何使用var来修复以下代码,例如
http://conceptf1.blogspot.com/2013/11/javascript-closures.html 或此循环内的JavaScript封闭-简单的实际示例

I found many topics explaining this problem, on how I can fix the following code by using var, like this one http://conceptf1.blogspot.com/2013/11/javascript-closures.html or this one JavaScript closure inside loops – simple practical example.

var funcs = [];        
for (var i = 0; i < 3; i++) {        //  let's create 3 functions
  funcs[i] = function() {            //  and store them in funcs
    console.log("My value: " + i);   //  each should log its value.
  };
}
for (var j = 0; j < 3; j++) {
  funcs[j]();                        //  and now let's run each one to see
}
// outputs 3 3 3

我真的不知道...

推荐答案

ES6让我们是块作用域,这意味着它像许多其他传统语言一样,在 {} 中拥有自己的作用域。但是相反, var 是代码中的全局变量。

ES6's let is block scope that means it has it's own scope inside {} like many other traditional languages. But in contrast var is a global variable in your code.

中,对于循环,函数刚被分配给 func [i] 3次,最终值为3,但是未执行。如果在第一个循环中执行该函数,则将获得预期的输出,例如:

In first for loop, function is just assigned to func[i] 3 times with final value 3 but not executed. If you execute the function inside first loop, you will get the expected output though like:

var funcs = [];
for (var i = 0; i < 3; i++) {      // let's create 3 functions
  funcs[i] = function() {          // and store them in funcs
    console.log("My value: " + i); // each should log its value.
  };
  funcs[i](); // execution of func
}

因此,重要的是

现在,在 funcs [j]()执行时第一次在您的代码中, i 的值已经是 3 。如果要记录增量值,则必须将其作为如下参数传递:

Now, by the time funcs[j]() is executed for the first time in your code, i's value is already 3. If you want to log incremented value, you have to pass that as an argument like the following:

var funcs = [];
for (var i = 0; i < 3; i++) {      // let's create 3 functions
  funcs[i] = function(j) {          // and store them in funcs
    console.log("My value: " + j); // each should log its value.
  };
}
for (var j = 0; j < 3; j++) {
  funcs[j](j);                      // and now let's run each one to see
}

这篇关于循环和闭包。 For和Var的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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