Array.prototype.find()未定义

ses*_*ses 3 javascript

这里

它说这应该工作:

function isPrime(element, index, array) {
    var start = 2;
    while (start <= Math.sqrt(element)) {
        if (element % start++ < 1) return false;
    }
    return (element > 1);
}

console.log( [4, 5, 8, 12].find(isPrime) ); // 5
Run Code Online (Sandbox Code Playgroud)

但是我最终遇到了一个错误:

TypeError: undefined is not a function
Run Code Online (Sandbox Code Playgroud)

这是为什么?

聚苯乙烯

我试图不使用underscorejs库,因为浏览器应该find()已经支持类似的功能。

lan*_*nte 5

使用填充工具来代替,只是复制粘贴下面的代码(从这个链接)启用find方法:

if (!Array.prototype.find) {
  Object.defineProperty(Array.prototype, 'find', {
    enumerable: false,
    configurable: true,
    writable: true,
    value: 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++) {
        if (i in list) {
          value = list[i];
          if (predicate.call(thisArg, value, i, list)) {
            return value;
          }
        }
      }
      return undefined;
    }
  });
}
Run Code Online (Sandbox Code Playgroud)