-1

获取满足Javascript条件的数组中第一个元素的高阶方法?

假设我有一个包含这些元素的数组:[1, 2, 3, 0, 3];

我想得到第一个大于的元素2

你如何使用高阶函数来实现这一点?

越紧凑越好。

如果我可以在haskell上做到这一点,我会这样做:

head $ filter condition array
for example:
head $filter (> 2) [1, 2, 3, 0, 3]
4

3 回答 3

2

像这样(小提琴):

function isBigEnough(element) {
  return element >= 2;
}
alert([1, 2, 3, 0, 3].filter(isBigEnough)[0]);

或者使用评论(小提琴)中提到的匿名函数的捷径:

alert([1,2,3,0,3].filter(function(e){return e>=2;})[0]);

文档

于 2013-11-02T20:58:18.543 回答
1

underscore is a JavaScript Library with useful utility functions and includes one called find, which would do exactly what you want.

http://underscorejs.org/#find

so you could write var x = _.find([1,2,3,0,3], function(v) { return v >= 2; });

于 2013-11-02T21:02:13.310 回答
0

You can use the some Array method to iterate the array until a condition is met (and then stop). Unfortunately it will only return whether the condition was met once, not by which element (or at what index) it was met.

function find(arr, test, ctx) {
    var result = null;
    arr.some(function(el, i) {
        return test.call(ctx, el, i, arr) ? (result = el), true : false;
    });
    return result;
}
于 2013-11-02T21:03:36.737 回答