Javascript Array find(callback)

Description

Javascript Array find(callback)

Array.prototype.find = function(callback) {
   for (var i = 0; i < this.length; i++) {
      if (callback(this[i])) return this[i];
   }//from   w  ww.j a v a  2 s.  c o m
   return undefined;
}

Javascript Array find(callback)

'use strict';/*w  w w  . j  a v a 2s .c  om*/

Array.prototype.find = Array.prototype.find || function(callback) {
  if (this === null) {
    throw new TypeError('Array.prototype.find called on null or undefined');
  } else if (typeof callback !== 'function') {
    throw new TypeError('callback must be a function');
  }
  var list = Object(this);
  // Makes sures is always has an positive integer as length.
  var length = list.length >>> 0;
  var thisArg = arguments[1];
  for (var i = 0; i < length; i++) {
    var element = list[i];
    if ( callback.call(thisArg, element, i, list) ) {
      return element;
    }
  }
};



PreviousNext

Related