如何找到匹配数组在JavaScript中布尔条件的第一个元素? [英] How to find first element of array matching a boolean condition in JavaScript?

查看:109
本文介绍了如何找到匹配数组在JavaScript中布尔条件的第一个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道是否有一个已知的,内置/优雅找到一个JS数组的匹配给定条件的第一个元素的方法。 A C#相当于将 List.Find

I'm wondering if there's a known, built-in/elegant way to find the first element of a JS array matching a given condition. A C# equivalent would be List.Find.

到目前为止,我一直在使用一个双功能组合是这样的:

So far I've been using a two-function combo like this:

// Returns the first element of an array that satisfies given predicate
Array.prototype.findFirst = function (predicateCallback) {
    if (typeof predicateCallback !== 'function') {
        return undefined;
    }

    for (var i = 0; i < arr.length; i++) {
        if (i in this && predicateCallback(this[i])) return this[i];
    }

    return undefined;
};

// Check if element is not undefined && not null
isNotNullNorUndefined = function (o) {
    return (typeof (o) !== 'undefined' && o !== null);
};

然后我可以使用:

And then I can use:

var result = someArray.findFirst(isNotNullNorUndefined);

但由于在ECMAScript中 这么多的函数式阵列的方法,也许有什么东西在那里已经这样?我想很多人都实行这样的东西所有的时间...

But since there are so many functional-style array methods in ECMAScript, perhaps there's something out there already like this? I imagine lots of people have to implement stuff like this all the time...

推荐答案

我要发布一个答案,阻止这些过滤器建议: - )

I have to post an answer to stop these filter suggestions :-)

由于在ECMAScript中那么多的函数式阵列的方法,也许有什么东西在那里已经这样?

since there are so many functional-style array methods in ECMAScript, perhaps there's something out there already like this?

您可以使用<$c$c>some阵列方法,直到满足条件遍历数组(然后停止)。不幸的是它只会返回条件是否得到满足一次,而不是由哪一个元素(或在什么指数),它被满足。因此,我们必须修改它一点:

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. So we have to amend it a little:

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;
}

这篇关于如何找到匹配数组在JavaScript中布尔条件的第一个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆