该方法ES6新增
。var testArr1 = [20,12,362,26,965,22,26,35];
var findItem1 = testArr1.find(function(item,index,arr){
return item>26});
console.log(findItem1 )//362
//也可以在对象数组中根据对象属性作为判断条件查找
var testArr2 = [{
name:'aaa',id:'111'},{
name:'bbb',id:'222'},{
name:'ccc',id:'333'}]
var findItem2 = testArr2.find(function(item,index,arr){
return item.name=='ccc'})
console.log(findItem2 )//{name:'ccc',id:'333'}
该方法ES6新增
。var testArr1 = [20,12,362,26,965,22,26,35];
var index1 = testArr1.findIndex(function(item,index,arr){
return item>100});
console.log(index1)//2
//也可以在对象数组中根据对象属性作为判断条件查找
var testArr2 = [{
name:'aaa',id:'111'},{
name:'bbb',id:'222'},{
name:'ccc',id:'333'}]
var index2 = testArr2 .findIndex(function(item,index,arr){
return item.name=='bbb'})
console.log(index2)//1
var testArr = [20,12,362,26,965,22,26,35];
var index1 = testArr.indexOf(26);
console.log(index1)//3
var index2 = testArr.indexOf(26,5);
console.log(index2)//6
var index3 = testArr.indexOf(26,7);
console.log(index3)//-1
总结:
1.find()与findIndex()参数与用法相同,不同的是find返回元素,findIndex返回索引;找不到时find返回undefined,findIndex返回-1.
2.findIndex()与indexOf(),findIndex比indexOf更强大一些,可以通过回调函数查找对象数组,indexOf只能查找数组中指定的值,不过indexOf可以指定开始查找位置的索引