JS提示 - 不要在循环中创建函数 [英] JS Hint - don't make functions within a loop

查看:552
本文介绍了JS提示 - 不要在循环中创建函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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


推荐答案

你可以移动功能在循环之外并将对它的引用传递给 map

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

或者,您可以使用JSHint指令忽略循环内的函数表达式。只需将其放在相关文件的顶部:

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 */

这篇关于JS提示 - 不要在循环中创建函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆