js 数组筛选方法使用整理_JavaScript常用数组元素搜索或过滤

一、常用方案介绍

  • 如果你想找到在符合特定条件的阵列中的所有项目,使用 filter。
  • 如果你想检查是否至少有一个项目符合特定的条件,请使用 find。
  • 如果你想检查一个数组包含一个特定的值,请使用 includes。
  • 如果要在数组中查找特定项目的索引,请使用indexOf

 

二、js 数组筛选方法使用整理

1.Array.filter()

在数组中查找满足特定条件的元素

let newArray = array.filter(callback);

newArray是返回的新数组
array 是我们要进行查找的数组本身
callback 是应用于数组每个元素的回调函数
如果数组中没有项目符合条件,则返回一个空数组。

案例:

        //1.在数组中查找满足特定条件的元素
        //返回子数组,如果找不到返回空数组 []
        const array = [{id:10,name:'张三'},{id:5,name:'李四'},{id:12,name:'王五'},{id:20,name:'赵六'}];
        const result = array.filter(element => element.id >= 100);
        console.log(result) //[11, 20]

 

 

2.Array.find()

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

let element = array.find(callback);

element -当前被遍历的元素(必填)
index -当前遍历的元素的索引/位置(可选)
array- 当前数组(可选)
但是请注意,如果数组中没有项目符合条件,则返回 undefined。

案例:

        //2.查找满足特定条件的第一个元素,如果找不到返回 undefined
        const array =[{id:10,name:'张三'},{id:5,name:'李四'},{id:12,name:'王五'},{id:20,name:'赵六'}];
        const greaterThanTen = array.find(element => element.id > 10);
        console.log(greaterThanTen)//11

 

3.Array.includes()

确定数组是否包含某个值,并在适当时返回 true 或 false

const includesValue = array.includes(valueToFind, fromIndex)

valueToFind 是要在数组中检查的值(必填)
fromIndex 是要开始从中搜索元素的数组中的索引或位置(可选)

案例:

        //3.确定数组是否包含某个值,并在适当时返回 true 或 false
        const array = [10, 11, 3, 20, 5];
        const includesTwenty = array.includes(20);
        console.log(includesTwenty)//true

 

4.Array.indexOf()

返回可以在数组中找到给定元素的第一个索引。如果数组中不存在该元素,则返回 -1

const indexOfElement = array.indexOf(element, fromIndex)

element 是要在数组中检查的元素(必填),并且
fromIndex 是要从数组中搜索元素的启始索引或位置(可选)
请务必注意,includes 和 indexOf 方法都使用严格的相等性('===')搜索数组。如果值的类型不同(例如4和'4'),它们将分别返回 false 和 -1

案例:

        //4.返回可以在数组中找到给定元素的第一个索引。如果数组中不存在该元素,则返回 -1
        const array = [10, 11, 3, 20, 5];
        const indexOfThree = array.indexOf(3);
        console.log(indexOfThree)//2

 

 

5.for 循环自定义查找,自由查找

 

更多:

JavaScript数组(三)数组对象使用整理

JavaScript数组(二)实例

Javascript数组(一)排序

posted @ 2024-03-05 20:09  天马3798  阅读(224)  评论(0编辑  收藏  举报