javascript - The for loop printing i mentioned in the let command in the ES6 standard introduction is 10. How to replace it without let?
阿神
阿神 2017-06-28 09:22:57
0
4
839

Recently I was reading Teacher Ruan Yifeng’s Introduction to ES Standards, and when I read the first chapter, I mentioned a piece of code

var a = [];
for (var i = 0; i < 10; i++) {
  a[i] = function () {
    console.log(i);
  };
}
a[6](); // 10

Using let here can solve this problem, but what if we use the ES5 method? IIFE can do it, but it prints it immediately.

阿神
阿神

闭关修行中......

reply all(4)
扔个三星炸死你
var a = [];
            for(var i = 0; i < 10; i++) {
                +function(i){
                    a[i] = function() {
                        console.log(i);
                    }
                }(i);
            };
a[6](); // 6

Closure problem

巴扎黑

You can use custom attributes
var a = [];
for (var i = 0; i < 10; i++) {

  var a[i].n = i;//自定义一个属性  n 
  a[i] = function () {
    console.log(this.n);
  };

}
a[6](); // 6

曾经蜡笔没有小新

This has nothing to do withletanything, I think the questioner wants to output 6, right?

But the question you asked seems completely inconsistent with what you want. I want to help you change the description of the question but I am a little helpless...

This is actually a closure problem. Mainly, let’s first analyze why 10 is output:

var a = [];
for(var i = 0; i < 10; i++) {
    a[i] = function () {
        console.log(i);
    };
}
a[6](); // 10
The role of

i in for is the entire external area, so when a[6]() is called, console.log(i) is actually run, and at this time because it has finished running Loop, the value of i is 10, so 10 is output.

As for what the questioner said, let can be solved because, in for, the variables declared by let only act inside for, so it will not cause i due to the completion of the loop. In the global scope it is 10.

In fact, what this question really examines should be closure.

var a = [];
for(var i = 0; i < 10; i++) {
    (function() {
        [i] = function () {
            console.log(i);
        }
    })(i);
}
a[6]();

The function of closure is similar to the previous function of let, which is to isolate local variables from each other without contaminating external variable values. Each closure is an independent area, and the closure passes parameters. It is only used internally by the closure, so the result of outputting 6 can also be achieved.

Peter_Zhu

You can use closures
http://www.softwhy.com/articl...
The second half of this article has already explained your questions

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!