美文网首页
Array.prototype.findIndex

Array.prototype.findIndex

作者: 玲儿珑 | 来源:发表于2021-03-24 14:05 被阅读0次

源码实现如下:

if (!Array.prototype.findIndex) {
  Object.defineProperty(Array.prototype, 'findIndex', {
    value: function(predicate) {
      if (this == null) {
        throw new TypeError('"this" is null or not defined');
      }
      var o = Object(this);
      var len = o.length >>> 0;
      if (typeof predicate !== 'function') {
        throw new TypeError('predicate must be a function');
      }
      var thisArg = arguments[1];
      var k = 0;
      while (k < len) {
        var kValue = o[k];
        if (predicate.call(thisArg, kValue, k, o)) {
          return k;
        }
        k++;
      }
      return -1;
    },
    configurable: true,
    writable: true
  });
}
let arr = [0, 1, 2, 3, 4, 5, 6, 7, 8]
arr.findIndex(n => n==5)

相关文章

网友评论

      本文标题:Array.prototype.findIndex

      本文链接:https://www.haomeiwen.com/subject/gnmxhltx.html