javascript - 为什么 If 语句在此循环中被视为函数?
问题描述
我一直在构建一个经常使用迭代的 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,它将打破循环,这就是我所做的。我返回一个在循环外声明的变量为真。这让我脱离了循环,并允许我在下面做逻辑。
我还应该指出,这也完全在一个循环中,因为我们正在迭代当前的搜索用户。我没有运行时或编译错误,这段代码运行良好,但也许我正在为将来的灾难做好准备。
任何想法为什么我会收到此错误?如果我错过了一些最佳实践?
解决方案
由于在您引用的第一行中currentSearch[i]
,因为[i]
我假设您在此处粘贴的整个代码块都在某种循环中,可能是for
.
Array.some
然后,您正在为触发错误的回调创建一个函数。
一种解决方案是将回调声明移到父循环之外,但由于您使用的是作用域中的变量,因此需要进行一些重构。
可能的解决方案
您可以在父循环(您在此处提供的代码之外的那个)之外声明一个检查子用户的函数。
//Please provide a better name for the function according to the context.
const checkChildUser = function (childUser) {
return this.id === childUser.id;
};
然后将其传递给Array.some
您正在使用的函数:
currentSearch[i].users.some(checkChildUser, user);
推荐阅读
- r - R - MCA(多重对应分析)格式错误的数据
- ruby-on-rails - 是否应该在关联请求外键值后自动更新输入表单?
- c++ - 链接器错误 - 不确定它没有链接什么
- python - 如何通过python在excel中按字母顺序对列进行排序?
- typescript - 在打字稿中返回两种类型的函数
- java - 如何调试 java.lang.StringIndexOutOfBoundsException:字符串索引超出范围错误?
- android - 如何在android中设置大于100的进度条的最大值
- elasticsearch - 是否可以在 ElasticSearch 的聚合脚本中访问日期范围值?
- amazon-web-services - 在 S3 上列出文件夹
- c# - 无法解析表达式'...:给定的参数与预期的参数不匹配”