Pure JS to lodash
Pure JS to lodash
我这里有一些不同的语句,希望您告诉我它们是否等效:
myApp.filter('myFilter', function() {
var result, i, sport, y, contains, league;
return function(sports, filterBy) {
if (angular.isUndefined(sports) || !filterBy) {
return sports;
}
filterBy = filterBy.toLowerCase();
result = [],
contains = function(haystack, needle) {
return haystack.toLowerCase().indexOf(needle) > -1;
};
for (i = 0; i < sports.length; i++) {
sport = sports[i];
if (contains(sport.name, filterBy)) {
result.push(sport);
continue;
} else {
for (y = 0; y < sport.leagues.length; y++) {
league = sport.leagues[y];
if (contains(league.name, filterBy)) {
result.push(sport);
break;
}
}
}
}
return result;
};
});
现在使用lodash:
myApp.filter('myFilter', function() {
var result, i, sport, y, contains, league;
return function(sports, filterBy) {
if (angular.isUndefined(sports) || !filterBy) {
return sports;
}
filterBy = filterBy.toLowerCase();
result = [],
contains = function(haystack, needle) {
return haystack.toLowerCase().indexOf(needle) > -1;
};
_.each(sports.length, function(sport) {
if (contains(sport.name, filterBy)) {
result.push(sport);
continue;
} else {
_.each(sport.leagues.length, function(league) {
if(contains(league.name, filterBy)) {
result.push(sport);
break;
}
});
}
});
只是我试图理解洛达什的逻辑。我在几乎纯JS中有这个功能,但一旦我试图将其翻译成lodash,我的应用程序就会崩溃,所以我想知道错误在哪里?
这里我有一个带有纯js函数的Plnkr,在库部分,你会看到我有underscore
,因为我不知道为什么lodash
没有加载,所以,我所做的只是:使用_.each
而不是for loop
将该函数转换为lodash
函数
在这种情况下,您不会使用"each"。此外,在"each"中,你不会得到"continue"或"break"。对我来说,我会使用"过滤器"来获得过滤后的结果。所以代码应该是这样的:
var result = sports.filter(function(sport){
return (
contains(sport.name, filterBy)
|| (
sport.leagues && sport.leagues.some(function(league) {
return contains(league.name, filterBy)
})
)
)
})
或用于lodash/下划线
var result = _.filter(sports, function(sport) {
return (
contains(sport.name, filterBy)
|| (
sport.leagues && _.some(sport.leagues, function(league) {
return contains(league.name, filterBy);
})
)
)
});
相关文章:
- 如果使用 lodash 将属性存在于另一个对象中,则向对象添加属性
- 节点Js:How to catch a“;没有这样的文件或目录“;读取线模块出错
- Lodash从集合创建集合
- Lodash 从值数组中查找数组中的值
- jQuery AJAX write to XML
- grep in JQuery to C#
- how to convert html <div> to pdf
- Node.js - POST to iFrame?
- Lodash懒惰链不'It’我不管用
- Lodash映射并返回唯一
- SVG xml to image
- Advantages to DOMParser vs template & innerHTML
- 应该如何在typescript中键入lodash流函数
- how to split a string with ','
- 使用lodash的特定对象特性值
- How to declare a Map containing certain properties with flow
- Php variable obj to js
- 如何在submit to sightly时将表单输入值作为参数传递给WCMUsePojo
- Looking for function identical to lodash's [_.set]()
- Pure JS to lodash