简体   繁体   English

是否有等效于Array.prototype.find()的Javascript,可在较旧的浏览器上运行?

[英]Is there a Javascript equivalent of Array.prototype.find() that works on older browsers?

Looking at the MDN definition of Array.prototype.find() , I was wondering if there is another javascript method to return the first object from an array based on a predicate, that also works on older browsers. 查看Array.prototype.find()的MDN定义,我想知道是否还有另一个javascript方法基于谓词从数组中返回第一个对象,该方法也适用于较旧的浏览器。

I am aware of 3rd party libraries such as _underscore and Linq.JS that do this, but curious if there is a more "native" approach. 我知道诸如_underscore和Linq.JS之类的第三方库可以执行此操作,但我想知道是否还有一种“本地”方法。

You can use MDN Polyfill which override this method in old browsers (Read the Tushar's comment). 您可以使用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;
  };
}

Check this library: https://github.com/iabdelkareem/LINQ-To-JavaScript 检查此库: https : //github.com/iabdelkareem/LINQ-To-JavaScript

It contains what you seek for [firstOrDefault] method for example: 它包含您要寻找的[firstOrDefault]方法,例如:

var ar = [{name: "Ahmed", age: 18}, {name: "Mohamed", age:25}, {name:"Hossam", age:27}];
var firstMatch = ar.firstOrDefault(o=> o.age > 20); //Result {name: "Mohamed", age:25}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM