如果遇到以下四种需求,则需要使用数据的查找方法:

  1. 获取满足特定条件的数组中的所有项目?
  2. 检查是否满足某种条件?
  3. 检查数组中是否有特定值?
  4. 数组中找到特定值得索引?

结合上述四种需求,有四种方法:

  1. filter
  2. find
  3. includes
  4. indexOf

Array.filter()

满足某种特定条件的所有数组

let newArray = array.filter(callback);

  1. const arr = [19,23,14,64,33,26,42];
  2. const greaterThan = arr.filter(ele => ele > 25);
  3. console.log(greaterThan);

Array.find()

满足特定条件的第一个元素

let ele = array.find(callback);

  1. const array = [1,4,6,8,9,23,45,17,24];
  2. const greaterThan = array.find(element => element > 20);
  3. console.log(greaterThan);

Array.includes()

确定数组中是否包含某个值,返回true or false

const includesValue = array.includes(valueToFind, fromIndex);

  1. const array = [10,22,34,13,38,2,63];
  2. const includesTwenty = array.incldues(38);
  3. console.log(includesTwenty); // true

Array.indexOf()

返回数组中给定元素的第一个索引,如果数组不存在改元素,返回-1

const indexOfElement = array.indexOf(element, fromIndex);

  1. const array = [1,2,5,8,9,41,34,67,53];
  2. const indexOfThree = array.indexOf(9);
  3. console.log(indexOfThree); // 4