我在 Nodejs 上遇到问题,我只需要在 item.IS_RACING === 1
时调用一次函数
看
_.map(recordsets, function(items) {
return _.map(items, function(item) {
if (item.IS_RACING === 1) {
_this.getRacing();
}
});
});
我有 _this.getRacing();
每次条件为 true
时都会被调用,但是如果有 20 个项目 IS_RACING === 1
,所以函数 _this.getRacing();
将被调用 20 次。我需要类似的东西,一旦应用程序检测到第一个 IS_RACING === 1
出现,然后仅触发一次 _this.getRacing();
。
有什么推荐吗?
最佳答案
正如 Pointy
在评论中指出的(抱歉),您真的不想使用 map()
来执行此操作。
从如何向其他开发人员解释问题的 Angular 来思考问题。
If any of the record sets has an item that is racing, I want to call
getRacing()
.
现在,编写代表您意图的代码。
var somethingIsRacing = _.some(recordsets, function(items) {
return _.some(items, function(item) {
return item.IS_RACING === 1;
});
});
if(somethingIsRacing) {
_this.getRacing();
}
此代码遵循称为命令查询分离的原则,您首先使用函数式编程风格查询以查找所需信息,然后使用命令式编程风格。
关于javascript - 在 map() 之后只调用一次函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34500670/