在javascript中是否有indexOf来搜索具有自定义比较功能的数组 [英] Is there an indexOf in javascript to search an array with custom compare function

查看:119
本文介绍了在javascript中是否有indexOf来搜索具有自定义比较功能的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要数组中第一个值的 index ,它与自定义比较函数匹配。

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

非常好 underscorej 有一个find函数,它返回一个函数返回true的第一个值,但我需要这个返回索引代替。是否有某个版本的indexOf可用于哪里,我可以传递一个用于比较的函数?

The very nice underscorej has a "find" function that returns the first value where a function returns true, but I would need this that returns the index instead. Is there a version of indexOf available somewhere, where I can pass a function used to comparing?

感谢您的任何建议!

推荐答案

以下是Underscore的方法 - 这使用一个接受迭代器函数的核心Underscore函数进行扩充:

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

这篇关于在javascript中是否有indexOf来搜索具有自定义比较功能的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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