javascript 给定一个数组和谓词,找到第一个匹配的元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11344345/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Given an array and predicate, find the first matching element
提问by ripper234
Is there an existing function that finds the first array element that matches some general predicate?
是否有一个现有的函数可以找到与某个一般谓词匹配的第一个数组元素?
$.fn.findFirstMatching = function(predicate) {
var result;
$.each(this, function(index, value) {
if (predicate(index, value)) {
result = {index: index, value: value};
}
});
if (result) {
return result;
}
};
采纳答案by MBO
If you use underscore.js, then you could use findmethod. It works even with jQuery objects storing collection of elements without problems.
如果您使用underscore.js,那么您可以使用find方法。它甚至适用于存储元素集合的 jQuery 对象,没有问题。
_.find(array, function(value,index) { /* predicate */ });
But besides this additional (but small) library you need to write it by yourself.
但是除了这个额外的(但很小的)库之外,您还需要自己编写它。
回答by Allain Lalonde
As of ES2015, you can use Array.prototype.find
从 ES2015 开始,您可以使用 Array.prototype.find
An example of using it looks like this:
使用它的示例如下所示:
// outputs the first odd number
console.log([2,4,10,5,7,20].find(x => x%2))
回答by turdus-merula
Another solution would be:
另一种解决方案是:
$.grep(yourArray, function (value, index) { return value == 42 } )[0]
Note that the order of the arguments should be value, index
请注意,参数的顺序应该是 value, index
Of course, using _underscoreis much more elegant and efficient (as $.grepapplies the predicate on the all items of the array, it doesn't stop after the first match), but anyway :)
当然,使用_underscore更加优雅和高效(因为$.grep将谓词应用于数组的所有项目,它不会在第一次匹配后停止),但无论如何:)
回答by icl7126
Custom implementation could be actually quite short and still readable:
自定义实现实际上可能很短但仍然可读:
function findFirst(array, predicate) {
for (var i = 0; i < array.length; i++) if (predicate(array[i])) return array[i];
}
This returns first item matching predicate (or undefined) and then stops iteration - this could be handy for huge arrays or if predicate function is complex.
这将返回匹配谓词(或未定义)的第一项,然后停止迭代 - 这对于大型数组或谓词函数很复杂时可能很方便。
回答by Gourav
You can easily find out the index of your searched element.
您可以轻松找到搜索元素的索引。