在 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);
}
除了forEach
,使用循环,使用多个or运算符或隐式调用some(predicate)
,有没有更聪明的方法来找到firstMatch
?最好是一个 JavaScript 函数(类似于 filterFirst(peddicate)
),它在第一次匹配时短路,类似于 C# 的 Enumerable.First()
实现?
FWIW,我的目标是 node.js/io.js 运行时。
最佳答案
无需重新发明轮子,正确的做法是使用.find
:
var firstMatch = ['a', 'b', 'c'].find(applyConditions);
如果您使用的浏览器不支持.find
,您可以polyfill it
关于javascript - 等价于 LINQ 的 Enumerable.First(predicate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28476629/