引言

在日常开发中,经常要在海量数据里面查找出自己想要的数据,在这里列举出查找数据的不同方法

查找数组

Array.prototype.filter(),返回一个包含所有满足条件的数组,如:

function isArray(value) {
  return value >= 10;
}
const filtered = [12, 5, 4].filter(isArray);    //[12]

const array = [1, 2, 3, 5];
console.log(array.filter(num => num > 3));     //[5]

在非数组对象上调用 filter()

const arrayLike = {
    length: 3,
    0: "a",
    1: "b",
    2: "c",
};
console.log(Array.prototype.filter.call(arrayLike, (x) => x <= "b"));    //[ 'a', 'b' ]

Array.prototype.find(),返回数组中满足提供的测试函数的第一个元素的值,如果没有就返回undefined

const array = [{ id: 1 }, { id: 2 }, { id: 3 }];
console.log(array.find(item => item.id === 2));     // { id: 2 }

同时也可以配合解构

console.log(array.find(({id}) => id === 2));     // { id: 2 }

在非数据对象中使用find(),Number.isInteger()判断该数据是否为整数

const arrayLike = {
length: 3,
0: 2,
1: 7.3,
2: 4,
};
console.log(Array.prototype.find.call(arrayLike, (x) => !Number.isInteger(x)));       // 7.3

Array.prototype.findIndex(),跟find()一样,返回第一个符合的数据,不过它是返回第一条数据的索引,如果找不到就返回-1

const array = [{ id: 1 }, { id: 2 }, { id: 3 }];
console.log(array.findIndex(item => item.id === 2));  //1

Array.prototype.findLast(),这个方法也是查找并返回第一条符合的数据,不过与find()不同的是,它是从后面开始找起,如果没有就返回undefined

Array.prototype.findLastIndex(),寻找下标

const arr = [5, 12, 50, 130, 44, 22];
console.log(array.findLast(item => item > 24));  //44

console.log(array.findLastIndex(item => item > 24));  //4 

Array.prototype.includes(),查找数组中是否有自己想要的数据,返回一个布尔值

const array = [1, 2, 3, 4, 5];
console.log(array.includes(3)); // true
console.log(array.includes(6)); // false

在语法中还有一个fromIndex参数,作用是代表开始搜索的索引,如果这个参数的值大于数组的长度,就不会搜索该数组,直接返回false

[1, 2, 3].includes(3, 3); // false

Array.prototype.indexOf(),寻找数组中第一个符合条件的元素索引,如果没有就返回-1,同样有一个fromIndex参数,值大于数组的长度时直接返回-1

const array = [1, 2, 3, 4, 5];
console.log(array.indexOf(3)); // 2
console.log(array.indexOf(6)); // -1

Array.prototype.keys(),返回一个数组,包含原数组中每一个索引的键,与Object.keys()只包含数组中实际存在的键不同,它是返回所有的键,还可以配合for...of使用

const arr = ["a", , "c"];
const bbb= [...arr.keys()];      //[0, 1, 2]

在数组中,有时候会有很多重复数据,有时候想知道某一个数据最后一次出现在哪,JavaScript提供了一个方法Array.prototype.lastIndexOf(),它也同样有一个fromIndex参数

const numbers = [2, 5, 9, 2];
numbers.lastIndexOf(2); // 3

温馨提示:不能使用这个来搜索数组中的NaN,也不能搜索稀疏数组中的空槽,会直接返回-1


除此之外,还可以用循环来查找,就不一一列出来了

好了,下班~

最后修改:2024 年 05 月 29 日
如果觉得我的文章对你有用,请随意赞赏