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

后端 未结 8 1741
执笔经年
执笔经年 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

    Here's the Underscore way to do it - this augments the core Underscore function with one that accepts an iterator function:

    // save a reference to the core implementation
    var indexOfValue = _.indexOf;
    
    // using .mixin allows both wrapped and unwrapped calls:
    // _(array).indexOf(...) and _.indexOf(array, ...)
    _.mixin({
    
        // return the index of the first array element passing a test
        indexOf: function(array, test) {
            // delegate to standard indexOf if the test isn't a function
            if (!_.isFunction(test)) return indexOfValue(array, test);
            // otherwise, look for the index
            for (var x = 0; x < array.length; x++) {
                if (test(array[x])) return x;
            }
            // not found, return fail value
            return -1;
        }
    
    });
    
    _.indexOf([1,2,3], 3); // 2
    _.indexOf([1,2,3], function(el) { return el > 2; } ); // 2
    

提交回复
热议问题