An overview of the
The find in js, findIndex indexof, includes can be used to find an item of the array, to compare the today. Test code address github.com/fanxuewen/e…
A, the find
Find returns undefined if the first item is found. This method does not change the original array. The usage is as follows
var findArr = [1, 2, 3, 4];
var res1 = findArr.find(item => {
return item > 2;
})
var res2 = findArr.find(item => {
return item > 10;
})
console.log('res1', res1);
console.log('res2', res2);
Copy the code
var findArr1 = [1, , 3];
console.log('--------find---------');
var res1 = findArr1.find((item, index) => {
console.log(item, The '-', index)
})
console.log('--------map---------');
findArr1.map((item, index) => {
console.log(item, The '-', index);
})
Copy the code
Second, the findIndex
FindIndex is used to find the first index that meets the criteria. If the index is found, the index is returned. If the index is not found, -1 is returned.
var findIndexArr = [1, 2, 3, 4];
var res1 = findIndexArr.findIndex(item => {
return item > 2;
})
var res2 = findIndexArr.findIndex(item => {
return item > 10;
})
console.log('res1', res1);
console.log('res2', res2);
//res1 2
//res2 -1
Copy the code
Third, indexof
The indexOf() method returns the first index in the array where a given element can be found, or -1 if none exists. Syntax: arr.indexof (searchElement[, startIndex = 0]) startIndex indicates the starting position of the searchElement. Default: 0.
var indexOfArr = [1, 2, 3, 4]; Indexofarr.indexof (2) //1 indexofarr.indexof (2,2)//-1 indexofarr.indexof (9) //-1Copy the code
Four, includes
The includes() method is used to determine whether an array contains a specified value, returning true if it does and false otherwise.
var includesArr = [1, 2, 3, 4];
includesArr.indexOf(2) //true
includesArr.indexOf(9) //false
Copy the code
Five, the summary
Determine if there is an item in the array to use indexof/includes