简体   繁体   English

Array.prototype.find() 未定义

[英]Array.prototype.find() is undefined

In here这里

it says that this should work:它说这应该有效:

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

But I end up having an error:但我最终遇到了一个错误:

TypeError: undefined is not a function

Why is that?这是为什么?

PS聚苯乙烯

I'm trying not to use underscorejs library since the browsers are supposed to support functions like find() already.我尽量不使用underscorejs库,因为浏览器应该已经支持find()类的功能。

Use the polyfill instead, just copy-paste the following code (from this link) to enable the find method:改用 polyfill,只需复制粘贴以下代码(来自链接)即可启用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;
    }
  });
}

As mentioned above, the Array.prototype.find method is an experimental feature proposed for ECMAScript 6. But if you want to use it, and you want a short polyfill that does the job, you can use this (from here ):如上所述,Array.prototype.find 方法是为 ECMAScript 6 提出的实验性功能。但是如果你想使用它,并且你想要一个短的 polyfill 来完成这项工作,你可以使用这个(来自 这里):

if (!Array.prototype.find) {
  Array.prototype.find = function (callback, thisArg) {
    "use strict";
    var arr = this,
        arrLen = arr.length,
        i;
    for (i = 0; i < arrLen; i += 1) {
        if (callback.call(thisArg, arr[i], i, arr)) {
            return arr[i];
        }
    }
    return undefined;
  };
}

Instead of .find(...) , you also can simply use .filter(...)[0] .除了.find(...) ,您还可以简单地使用.filter(...)[0] (For IE >= 9) (对于 IE >= 9)

Example:例子:

 function isEven(x) { return x % 2 == 0; } console.log([3, 4, 5].find(isEven)); // 4 console.log([3, 4, 5].filter(isEven)[0]); // 4

Reference: Array.prototype.filter()参考: Array.prototype.filter()

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

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