no-loop-func

禁止在循环语句中包含不安全引用的函数声明

由于函数在循环周围创建闭包的方式,在循环中编写函数往往会导致错误。例如:

for (var i = 0; i < 10; i++) {
    funcs[i] = function() {
        return i;
    };
}

在这种情况下,您会期望在循环中创建的每个函数都返回不同的数字。实际上,每个函数都返回 10,因为这是作用域中 i 的最后一个值。

letconst 缓解了这个问题。

/*eslint-env es6*/

for (let i = 0; i < 10; i++) {
    funcs[i] = function() {
        return i;
    };
}

在这种情况下,循环中创建的每个函数都按预期返回不同的数字。

规则详情

pa2a+XfHKvjQguSbUbB2XWmrEM6Fd7Q0gHPev+BwKb6QFF3c0JWJyYOKmDO58UKpxCreSOeHMgr8ijkPsHLdsVosuqoS2rqWn0Todq/Z6aHWaFGYkQHKVNxHFiv5tXuvTBoY+JnrtxK5SuifesmB9XQISMsOg/5rwkZrtjtSumO+81LtFNfVLcRPZ8sIVoinS2q4HnLlJh0E4xWD7kx3HJDCYct7sHahczHjGWbunPRQGFcTXprFb1ggnF/mlFNEQEFgmB5owAEXTQJ00nKdhrV+smEbPG3U1aPB9IDXZqcWz22XZ4qzeFCZiFAPdb3uax92GYdUUE36gFrfSfq1w2sBizKUxu2lJTGiGZ3FdP89CLWs0T2Ar2XC8p8VzF1I

ZM+7UkzS+Zxu8bvSqSbq6Ir1wALhIfB5LXURAg7sQ/dreY9Nm01a4anx9Ae1CjTQxkUPJEihiMFDAbo9KswUDriLhTB4oI1cBiCILhXO3JBAkUSnt9Z7SIeYTFgEOltqzGvklU6RocZeBCge5E4s5g==

k7HkpyhTRoT9T3bsrVJ1W9IUT56r3GvYicL0qS8XjwbDvDXG9eGk/CkswpMjh9k+

/*eslint no-loop-func: "error"*/
/*eslint-env es6*/

for (var i=10; i; i--) {
    (function() { return i; })();
}

while(i) {
    var a = function() { return i; };
    a();
}

do {
    function a() { return i; };
    a();
} while (i);

let foo = 0;
for (let i = 0; i < 10; ++i) {
    //Bad, `foo` is not in the loop-block's scope and `foo` is modified in/after the loop
    setTimeout(() => console.log(foo));
    foo += 1;
}

for (let i = 0; i < 10; ++i) {
    //Bad, `foo` is not in the loop-block's scope and `foo` is modified in/after the loop
    setTimeout(() => console.log(foo));
}
foo = 100;

f/g6SKVZdhoBiPVtnee0m+uPEv1T4kMgIaFUpxdtFwzAZHGBqJ5dJxRHxHHP/cP8

/*eslint no-loop-func: "error"*/
/*eslint-env es6*/

var a = function() {};

for (var i=10; i; i--) {
    a();
}

for (var i=10; i; i--) {
    var a = function() {}; // OK, no references to variables in the outer scopes.
    a();
}

for (let i=10; i; i--) {
    var a = function() { return i; }; // OK, all references are referring to block scoped variables in the loop.
    a();
}

var foo = 100;
for (let i=10; i; i--) {
    var a = function() { return foo; }; // OK, all references are referring to never modified variables.
    a();
}
//... no modifications of foo after this loop ...