Home  >  Q&A  >  body text

javascript - The for loop printing i mentioned in the let command in the ES6 standard introduction is 10. How to replace it without let?

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.

阿神阿神2694 days ago868

reply all(4)I'll reply

  • 扔个三星炸死你

    扔个三星炸死你2017-06-28 09:24:57

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

    Closure problem

    reply
    0
  • 巴扎黑

    巴扎黑2017-06-28 09:24:57

    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

    reply
    0
  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-06-28 09:24:57

    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.

    reply
    0
  • 天蓬老师

    天蓬老师2017-06-28 09:24:57

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

    reply
    0
  • Cancelreply