Javascript Array find(predicate)

Description

Javascript Array find(predicate)

Array.prototype.find = function(predicate) {
 var foundAll = this.findAll(predicate);
 if (foundAll.length == 0) {
  return null;/*from   www  .ja  va 2  s. co m*/
 } else {
  return foundAll[0];
 }
};

Javascript Array find(predicate)

Array.prototype.find = Array.prototype.find || function (predicate) {
    'use strict';
    if (this === null) {
        throw new TypeError('Array.prototype.find called on null or undefined');
    }//from   w w w.j a  v  a2  s  . c om

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



PreviousNext

Related