find: 根据传入的条件函数,返回符合条件的第一项
var arr = [{id: 1, name: 'zs', age: 18},{id: 2, name: 'zs', age: 17},{id: 3, name: 'ls', age: 16},{id: 4, name: 'ls', age: 15}]Array.prototype._find_ = function(cb){for(var i=0; i< this.length; i++){if(cb(this[i],i)){return this[i];}}}var ret1 = arr._find_(function (item, index){return item.age === 17;})var ret2 = arr._find_(function (item, index){return item.id === 1;})var ret3 = arr._find_(function (item, index){return item.name === "zs";})console.log(ret1, ret2 ,ret3);
findIndex: 根据传入的条件函数,返回符合条件的第一个下标
var arr = [{id: 1, name: 'zs', age: 18},{id: 2, name: 'zs', age: 17},{id: 3, name: 'ls', age: 16},{id: 4, name: 'ls', age: 15}]Array.prototype._findIndex_ = function(cb){for(var i=0; i< this.length; i++){if(cb(this[i],i)){return i;}}}var ret1 = arr._findIndex_(function (item, index){return item.age === 17;})var ret2 = arr._findIndex_(function (item, index){return item.id === 1;})var ret3 = arr._findIndex_(function (item, index){return item.name === "zs";})console.log(ret1, ret2 ,ret3);