我想知道是否有一个已知的,内置/优雅的方法来找到一个JS数组的第一个元素匹配给定的条件。c#的等效程序是List.Find。

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

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

然后我可以用:

var result = someArray.findFirst(isNotNullNorUndefined);

但既然ECMAScript中有这么多函数风格的数组方法,也许已经有这样的东西了?我想很多人都必须实现这样的东西……


当前回答

使用过滤器并从结果数组中获得第一个索引如何?

var result = someArray.filter(isNotNullNorUndefined)[0];

其他回答

使用findIndex。下面是完整的例子:

function find(arr, predicate) {
    foundIndex = arr.findIndex(predicate);
    return foundIndex !== -1 ? arr[foundIndex] : null;
}

用法如下(我们想找到数组中第一个具有id === 1属性的元素)。

var firstElement = find(arr, e => e.id === 1);

从ECMAScript 6开始,你可以使用Array.prototype.find。这可以在Firefox(25.0)、Chrome(45.0)、Edge(12)和Safari(7.1)中实现,但不能在Internet Explorer或其他一堆旧的或不常见的平台上实现。

例如,下面的x为106:

Const x =[100,101,102,103,104,105,106,107,108,109]。Find (function (el) { 返回el > 105; }); console.log (x);

If you want to use this right now but need support for IE or other unsupporting browsers, you can use a shim. I recommend the es6-shim. MDN also offers a shim if for some reason you don't want to put the whole es6-shim into your project. For maximum compatibility you want the es6-shim, because unlike the MDN version it detects buggy native implementations of find and overwrites them (see the comment that begins "Work around bugs in Array#find and Array#findIndex" and the lines immediately following it).

foundElement = myArray[myArray.findIndex(element => //condition here)];

使用过滤器并从结果数组中获得第一个索引如何?

var result = someArray.filter(isNotNullNorUndefined)[0];

简介:

为了找到数组中第一个符合布尔条件的元素,我们可以使用ES6 find() find()位于Array上。原型,所以它可以用于每个数组。 Find()接受一个测试布尔条件的回调。函数返回值(不是索引!)

例子:

Const array = [4,33,8,56,23]; Const found = array。Find (element => { 返回元素> 50; }); console.log(发现);/ / 56