Javascript 相当于 LINQ 的 Enumerable.First(predicate)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28476629/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Equivalent to LINQ's Enumerable.First(predicate)
提问by vulcan raven
In C#, we have Enumerable.First(predicate). Given this JavaScript code:
在 C# 中,我们有Enumerable.First(predicate). 鉴于此 JavaScript 代码:
function process() {
var firstMatch = ['a', 'b', 'c'].filter(function(e) {
return applyConditions(e);
}).shift();
if(!firstMatch) {
return;
}
// do something else
}
function applyConditions(element) {
var min = 97;
var max = 122;
var random = Math.floor(Math.random() * (max - min + 1) + min);
return element === String.fromCharCode(random);
}
other than forEach, using loop, using multiple or operators or implicitly calling some(predicate), is there a smarter way of finding the firstMatch? Preferably a JavaScript function (something like filterFirst(pedicate)) which short-circuits on first match resembling C#'s Enumerable.First()implementation?
除了forEach使用循环、使用多个或运算符或隐式调用之外some(predicate),是否有更智能的方法来查找firstMatch?最好是一个 JavaScript 函数(类似于filterFirst(pedicate)),它在第一次匹配时短路,类似于 C# 的Enumerable.First()实现?
FWIW, I am targeting node.js / io.js runtimes.
FWIW,我的目标是 node.js / io.js 运行时。
回答by Benjamin Gruenbaum
No need to reinvent the wheel, the correct way to do it is to use .find:
无需重新发明轮子,正确的方法是使用.find:
var firstMatch = ['a', 'b', 'c'].find(applyConditions);
If you're using a browser that does not support .findyou can polyfill it
回答by xzyfer
You could emulate this in the case where you want to return the first truthyvalue with reduce.
如果您想用 返回第一个真值,您可以模拟这一点reduce。
['a', 'b', 'c'].reduce(function(prev, curr) {
return prev || predicate(curr) && curr;
}, false);
edit:made more terse with @BenjaminGruenbaum suggestion
编辑:用@BenjaminGruenbaum 建议更简洁
回答by toddmo
LINQusers call firstand firstOrDefaulta lot with no predicate, which is not possible with find. So,
LINQ用户调用first和firstOrDefault很多没有谓词,这是不可能的find。所以,
first() {
var firstOrDefault = this.firstOrDefault();
if(firstOrDefault !== undefined)
return firstOrDefault;
else
throw new Error('No element satisfies the condition in predicate.');
}
firstOrDefault() {
return this.find(o => true);
}

