Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array.prototype.find() is undefined

Tags:

javascript

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?

P.S.

I'm trying not to use underscorejs library since the browsers are supposed to support functions like find() already.

like image 454
ses Avatar asked Jan 11 '23 10:01

ses


1 Answers

Use the polyfill instead, just copy-paste the following code (from this link) to enable the find method:

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;
    }
  });
}
like image 175
lante Avatar answered Jan 21 '23 08:01

lante