Javascript 数组查找备选方案

Javascript array find alternative

我正在寻找数组的 find() 方法的替代方法。我在 Android 浏览器上使用它,但 Array.prototype.find() 在那里不起作用。 Definition Array Support

var test= this.arrayOfValues.find(function (value) {
            return (value.name === device.value)
});

如果你不太关心自己编程,并且如果indexOf is somehow not usable, have a look at Underscore.js#find. As an alternative, as @NinaScholz recommended in the comments, use the Polyfill from mozilla.org:

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;
  };
}