是否有一个Javascript等效的Array.prototype.find()适用于旧浏览器?

kob*_*490 0 javascript linq arrays predicate

看看Array.prototype.find()的MDN定义,我想知道是否有另一种javascript方法可以基于谓词从数组中返回第一个对象,这也适用于旧版浏览器.

我知道第三方库,如_underscore和Linq.JS这样做,但好奇是否有更"本机"的方法.

cab*_*rog 5

您可以使用MDN Polyfill在旧浏览器中覆盖此方法(阅读Tushar的评论).

 if (!Array.prototype.find) {
  Array.prototype.find = function(predicate) {
    if (this === null) {
      throw new TypeError('Array.prototype.find called on null or undefined');
    }
    if (typeof predicate !== 'function') {
      throw new TypeError('predicate must be a function');
    }
    var list = Object(this);
    var length = list.length >>> 0;
    var thisArg = arguments[1];
    var value;

    for (var i = 0; i < length; i++) {
      value = list[i];
      if (predicate.call(thisArg, value, i, list)) {
        return value;
      }
    }
    return undefined;
  };
}
Run Code Online (Sandbox Code Playgroud)