var searchArr = [{id:1,text:"foo"},{id:2,text:"bar"}];
var count = 0;
var filteredEl = _.find(searchArr,function(arrEl){
count = count +1;
if(arrEl.id === 1 ){
return arrEl;
}
});
console.log(filteredEl);
//since we are searching the first element in the array, the count will be one
console.log(count);
//output: filteredEl : {id:1,text:"foo"} , count: 1
**老**
如果你想有条件地跳出循环,使用_。过滤API而不是_.each。下面是一个代码片段
var searchArr = [{id:1,text:"foo"},{id:2,text:"bar"}];
var filteredEl = _.filter(searchArr,function(arrEl){
if(arrEl.id === 1 ){
return arrEl;
}
});
console.log(filteredEl);
//output: {id:1,text:"foo"}