JS Hint - don't make functions within a loop

后端 未结 3 1789
Happy的楠姐
Happy的楠姐 2020-12-23 19:14

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 : Co         


        
3条回答
  •  醉梦人生
    2020-12-23 19:28

    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)
                 });
    }
    

提交回复
热议问题