【发布时间】:2018-10-19 16:30:41
【问题描述】:
我一直在构建一个经常使用迭代的 React 应用程序。我正在使用 JSLint 并收到烦人的警告:
不要在循环中创建函数
在以下循环中:
if(currentSearch[i].users.length > 0) {
var matched = false;
//I hate how JSLint just can't handle setting a variable to true within a function
//this is loop where I get the warning
currentSearch[i].users.some(childUser => {
if(childUser.id === user.id) {
return matched = true;
}
})
//^^^^^ Warning
if(!matched) {
var alert = new AlertObject(user,currentSearch[i],true,false);
alerts.push(alert);
}
}
我不认为我在循环中设置了一个函数?我正在使用 array.some 函数,如果我返回 true,它将打破循环,这就是我所做的。我返回一个在循环外声明的变量为真。这让我脱离了循环,并允许我在下面做逻辑。
我还应该指出,这也完全在一个循环中,因为我们正在迭代当前的搜索用户。我没有运行时或编译错误,这段代码运行良好,但也许我正在为将来的灾难做好准备。
任何想法为什么我会收到此错误?如果我遗漏了一些最佳实践?
【问题讨论】:
-
使用
some的方式多么奇怪:)。您不需要在回调之外改变变量。只需使用返回的值const matched = currentSearch[i].users.some(childUser => childUser.id === user.id)
标签: javascript reactjs jslint