【发布时间】:2015-04-13 03:20:16
【问题描述】:
在 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,使用循环,使用多个或运算符或隐式调用some(predicate),有没有更聪明的方法来找到firstMatch?最好是一个 JavaScript 函数(类似于 filterFirst(pedicate)),它在第一次匹配时短路,类似于 C# 的 Enumerable.First() 实现?
FWIW,我的目标是 node.js / io.js 运行时。
【问题讨论】:
标签: javascript arrays node.js linq filter