如果遇到以下四种需求,则需要使用数据的查找方法:
- 获取满足特定条件的数组中的所有项目?
- 检查是否满足某种条件?
- 检查数组中是否有特定值?
- 数组中找到特定值得索引?
结合上述四种需求,有四种方法:
- filter
- find
- includes
- indexOf
Array.filter()
满足某种特定条件的所有数组
let newArray = array.filter(callback);
const arr = [19,23,14,64,33,26,42];const greaterThan = arr.filter(ele => ele > 25);console.log(greaterThan);
Array.find()
满足特定条件的第一个元素
let ele = array.find(callback);
const array = [1,4,6,8,9,23,45,17,24];const greaterThan = array.find(element => element > 20);console.log(greaterThan);
Array.includes()
确定数组中是否包含某个值,返回true or false
const includesValue = array.includes(valueToFind, fromIndex);
const array = [10,22,34,13,38,2,63];const includesTwenty = array.incldues(38);console.log(includesTwenty); // true
Array.indexOf()
返回数组中给定元素的第一个索引,如果数组不存在改元素,返回-1
const indexOfElement = array.indexOf(element, fromIndex);
const array = [1,2,5,8,9,41,34,67,53];const indexOfThree = array.indexOf(9);console.log(indexOfThree); // 4
