在javascript中是否有indexOf来搜索具有自定义比较功能的数组

Ped*_* T. 26 javascript indexof underscore.js

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

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

谢谢你的任何建议!

nra*_*itz 26

这是Underscore的方法 - 它使用一个接受迭代器函数的核心Underscore函数来增强它:

// 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
Run Code Online (Sandbox Code Playgroud)

  • 注意:underscore.js自原始帖子和答案后添加了[findIndex](http://underscorejs.org/#findIndex)函数. (4认同)
  • @mintsauce - OP引用了Underscore,这就是我提供基于Underscore的解决方案的原因.W/r/t全局引用,这是一个片段,而不是一个插入模块; 用户的工作是将其包装或以适合其应用的方式进行设置.W/r/t错误 - 是的,这就是为什么我更喜欢编写无错误的代码:). (3认同)

Hus*_*sky 10

ECMAScript 2015中有一个标准功能Array.prototype.findIndex().目前,除了Internet Explorer之外,它还在所有主流浏览器中实现.

这是一个polyfill,由Mozilla开发者网络提供:

// https://tc39.github.io/ecma262/#sec-array.prototype.findIndex
if (!Array.prototype.findIndex) {
  Object.defineProperty(Array.prototype, 'findIndex', {
    value: function(predicate) {
     // 1. Let O be ? ToObject(this value).
      if (this == null) {
        throw new TypeError('"this" is null or not defined');
      }

      var o = Object(this);

      // 2. Let len be ? ToLength(? Get(O, "length")).
      var len = o.length >>> 0;

      // 3. If IsCallable(predicate) is false, throw a TypeError exception.
      if (typeof predicate !== 'function') {
        throw new TypeError('predicate must be a function');
      }

      // 4. If thisArg was supplied, let T be thisArg; else let T be undefined.
      var thisArg = arguments[1];

      // 5. Let k be 0.
      var k = 0;

      // 6. Repeat, while k < len
      while (k < len) {
        // a. Let Pk be ! ToString(k).
        // b. Let kValue be ? Get(O, Pk).
        // c. Let testResult be ToBoolean(? Call(predicate, T, « kValue, k, O »)).
        // d. If testResult is true, return k.
        var kValue = o[k];
        if (predicate.call(thisArg, kValue, k, o)) {
          return k;
        }
        // e. Increase k by 1.
        k++;
      }

      // 7. Return -1.
      return -1;
    },
    configurable: true,
    writable: true
  });
}
Run Code Online (Sandbox Code Playgroud)


Nat*_*nax 7

你可以这样做:

Array.prototype.myIndexOf = function(f)
{
    for(var i=0; i<this.length; ++i)
    {
        if( f(this[i]) )
            return i;
    }
    return -1;
};
Run Code Online (Sandbox Code Playgroud)

关于Christian的评论:如果你使用具有不同相同签名和不同功能的自定义JavaScript方法覆盖标准JavaScript方法,则可能会发生不好的事情.如果您正在使用可能依赖于原始数据的第三方库,例如Array.proto.indexOf,则尤其如此.所以,是的,你可能想把它称之为别的东西.

  • 感谢您的关注.我也相信第二次机会.;)请强调为什么`Array.prototype.indexOf(function)`是错误的方法,我会给你upvote. (2认同)