不要在循环中创建函数. - jslint错误

ama*_*eur 4 javascript jquery jslint jshint

我收到这个jslint错误

不要在循环中创建函数.

我无法更改导致此问题的JavaScript - 但是我不能,因为修改它的限制.

因此,我想将此验证转换为在特定的javascript文件中检查此错误.

这可能是为了这个js错误吗?

Joe*_*Joe 8

不,该检查不是可选的.

可能的解决方法:

// simple closure scoping i to the function.
for(var i = 0; i < 10; i++) {
    (function (index) {
         console.log(index);
     }(i));
}
// this works, however it's difficult to site read and not a blast to debug
Run Code Online (Sandbox Code Playgroud)

一个办法:

// same exact output
function logger(index) {
    console.log(index);
}

// same output. Minus declaring all vars at the
// top of the function and console this passes jslint.
for(var i = 0; i < 10; i++) {
    logger(i);
}
Run Code Online (Sandbox Code Playgroud)

  • JSLint并不是所有javasript的终结.这是一个非常好的指南.有些情况下甚至需要使用最恶劣的javascript函数,比如eval. (2认同)