javascript - 等价于 LINQ 的 Enumerable.First(predicate)

标签 javascript arrays node.js linq filter

在 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/

相关文章:

javascript - Passport 、蒙戈、 express 、购物车教程在发布请求后点击提交时滞后

javascript - s3.getObject().createReadStream() : How to catch the error?

javascript - 全选/取消全选页面中的复选框

javascript - 如何在reactjs中添加onMouseOver、onMouseEnter?

javascript - 尝试使用 javascript 将文件缩略图设置到 Google Drive

javascript - 如何将数组导入到javascript中的函数中?

php - 检查数组值是否已设置且为空

javascript - 如何判断数组中的元素是否重复?

javascript - 我有一个 id 数组,需要更新对象文档 mongodb 中数组中的匹配对象,如果没有则插入

javascript - 如何将时刻日期转换为字符串并删除时刻对象