JS提示 - 不要在循环中创建函数

时间:2022-08-17 20:04:12

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

我无法解决JSHint的错误消息。这是我正在使用的循环:

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

2 个解决方案

#1


96  

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指令忽略循环内的函数表达式。把它放在有问题的文件的顶部:

/*jshint loopfunc: true */

#2


5  

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

#1


96  

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指令忽略循环内的函数表达式。把它放在有问题的文件的顶部:

/*jshint loopfunc: true */

#2


5  

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