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

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

    Here comes the coffeescript version of nrabinowitz's code.

    # save a reference to the core implementation
    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: (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 item, i in array
                return i if (test(item))
            # not found, return fail value
            return -1
    })
    

提交回复
热议问题