一、常用方案介紹:
- 如果你想找到在符合特定條件的陣列中的所有項目,使用 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 循環自定義查找,自由查找
更多: