简体   繁体   English

Jshint:循环中的匿名函数(问题)

[英]Jshint: Anonmyous function within a loop (Issue)

My problem is similar to JSHint won't let me use 'forEach' in a 'for' loop 我的问题类似于JSHint,不允许我在“ for”循环中使用“ forEach”

We have about 2k JS lines in currently project, recently included jshint checking, one common issue is the below sample code would throw 当前项目中大约有2k JS行,最近包含了jshint检查,一个常见的问题是下面的示例代码会抛出

Don't make functions within a loop. 不要在循环内创建函数。

sample code: 样例代码:

var s1 = '12345'.split('');
var oo = { a: s1, b: s1, c: s1};

function odd(obj){
    var tmp = [];
    for (var key in obj){
        obj[key].forEach( function(val){
            if(val%2>0) tmp.push(val);
        });
    }
    return tmp;
}


odd(oo);

my fix was: 我的解决方法是:

function odd(obj){
    var tmp = [], tmpFn;
    tmpFn = function(val){
        if(val%2>0) tmp.push(val);
    };
    for (var key in obj){
        obj[key].forEach(tmpFn);
    }
    return tmp;
}

I have checked, this works, but I am unsure if this is the right way to fix old code, would there be any unwanted side effects from this fix? 我已经检查过了,这个方法行得通,但是我不确定这是否是修复旧代码的正确方法,此修复程序会不会有有害的副作用? or should I just ignore the warning, as the old code looks much cleaner? 还是应该忽略警告,因为旧代码看起来更干净?

EDIT : I missed a for loop, updated sample code with it. 编辑 :我错过了for循环,用它更新了示例代码。

Don't ignore that warning, it's really unnecessary to create a new function for each run of your loop. 不要忽略该警告,实际上不必为每次循环运行都创建一个新函数。

This approach is better, and as long as you stay within the odd() function with the definition, it won't have any side effects, it will see the same variable states as it would as an anonymous function passed to forEach. 这种方法更好,只要您将它保留在带有定义的odd()函数中,它就不会有任何副作用,它将看到与传递给forEach的匿名函数相同的变量状态。

Edit: even if you do decide to ignore that warning, do it consistently - either use a jshint configuration which doesn't consider this a mistake, or add a jshint comment to temporarily disable this warning type inside the code (use jshint --verbose to get the warning code for selective toggling), don't let any displayed jshint warning go without notice, that defeats the purpose of having code analysis in the first place. 编辑:即使您决定忽略该警告,也要始终如一地执行-使用不会将其视为错误的jshint配置,或者添加jshint注释以在代码内临时禁用此警告类型(使用jshint --verbose (以获得用于选择性切换的警告代码),请不要让任何显示的jshint警告在没有通知的情况下进行,这首先会破坏进行代码分析的目的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM