给定一个数组和谓词,找到第一个匹配元素

rip*_*234 18 javascript jquery

是否存在找到与某个通用谓词匹配的第一个数组元素的现有函数?

$.fn.findFirstMatching = function(predicate) {
    var result;
    $.each(this, function(index, value) {
        if (predicate(index, value)) {
            result = {index: index, value: value};
        }
    });
    if (result) {
        return result;
    }
};
Run Code Online (Sandbox Code Playgroud)

tur*_*ula 17

另一种解决方案是:

$.grep(yourArray, function (value, index) { return value == 42 } )[0]
Run Code Online (Sandbox Code Playgroud)

请注意,参数的顺序应该是 value, index

jQuery.grep的文档.

当然,使用_underscore更加优雅和高效(因为$ .grep将谓词应用于数组的所有项目,它在第一次匹配后不会停止),但无论如何:)


All*_*nde 17

从ES2015开始,您可以使用 Array.prototype.find

使用它的一个例子如下:

// outputs the first odd number
console.log([2,4,10,5,7,20].find(x => x%2))
Run Code Online (Sandbox Code Playgroud)


MBO*_*MBO 11

如果你使用underscore.js,那么你可以使用find方法.即使jQuery对象存储元素集合也没有问题.

_.find(array, function(value,index) { /* predicate */ });
Run Code Online (Sandbox Code Playgroud)

但除了这个额外的(但很小的)库,你需要自己编写它.