Is there an indexOf in javascript to search an array with custom compare function

后端 未结 8 1744
执笔经年
执笔经年 2020-12-05 18:05

I need the index of the first value in the array, that matches a custom compare function.

The very nice underscorej has a \"find\" function that returns the

8条回答
  •  生来不讨喜
    2020-12-05 18:42

    The javascript array method filter returns a subset of the array that return true from the function passed.

    var arr= [1, 2, 3, 4, 5, 6],
    first= arr.filter(function(itm){
        return itm>3;
    })[0];
    alert(first);
    
    if you must support IE before #9 you can 'shim' Array.prototype.filter-
    
    Array.prototype.filter= Array.prototype.filter || function(fun, scope){
        var T= this, A= [], i= 0, itm, L= T.length;
        if(typeof fun== 'function'){
            while(i

提交回复
热议问题