JS Hint - don't make functions within a loop

风格不统一 提交于 2019-11-28 18:17:50

问题


I can not get around JSHint's error message. Here is the loop I am using:

for (i = 0; i < Collection.length; i += 4) {
    data.push({
        items : Collection.slice(i, i + 4).map(function(item) {
            return {
                id: item[0],
                title: item[1],
            };
        })
    });
}

回答1:


You can just move the function outside the loop and pass a reference to it to map:

function mapCallback(item) {
    return {
        id : item[0],
        title : item[1],
    };
}
for (i = 0; i < Collection.length; i += 4) {
    data.push({
        items: Collection.slice(i, i + 4).map(mapCallback)
    });
}

Alternatively, you can use a JSHint directive to ignore function expressions inside loops. Just put this at the top of the file in question:

/*jshint loopfunc: true */



回答2:


Declaring a function in a loop is messy, and potentially error prone. Instead, define the function once, and then enter the loop.

var objMaker = function(item) {
    return {
        id : item[0],
        title : item[1],
    };
};

for (i = 0; i < Collection.length; i += 4) {
    data.push({
                  items : Collection.slice(i, i + 4).map(objMaker)
             });
}



回答3:


People say "Declaring a function in a loop is messy and potentially error-prone", but functions within loops is what directly instructed in, for example, Array.prototype.forEach method. Just because the word "function" should theoretically mean defining it anew in every forEach call it does not mean it is actually defined each time by the Javascript engine.

The same goes for outer loops since engines have "lazy" processing of instructions. They are not going to redefine the whole forEach/Map/etc construct-instruction anew if nothing really changed about it, they will just feed new arguments to it.

The times of ancient JS engines which were clueless about such simple things as well as of code context are long gone. And yet we are getting this ancient warning which was conceived when functions were not yet capable of being passed as arguments as in the cases of forEach or Map.



来源:https://stackoverflow.com/questions/13082302/js-hint-dont-make-functions-within-a-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!