一、簡介
Array.filter是ES6新增的高階函數,它接收一個回調函數,該函數作用於數組的每一個元素,返回true則保留該元素,返回false則過濾掉該元素,最終返回一個新的數組。
二、語法
array.filter(function(currentValue, index, arr), thisValue)
- currentValue:當前遍歷到的數組元素
- index:當前遍歷到的數組元素的下標
- arr:被遍歷的數組
- thisValue:可選,指定回調函數中的this對象
三、應用場景
在實際開發中,Array.filter廣泛應用於從數組中獲取指定條件的元素,例如:
- 從一個對象數組中篩選出滿足指定條件的對象
- 從一個字元串數組中篩選出指定字元開頭的字元串
- 從一個數字數組中篩選出大於某個特定數字的元素
四、實例一:篩選對象數組
假設有一個人員信息對象數組,需要篩選出所有年齡大於等於18歲且性別為女性的人員:
const persons = [
{ name: '張三', age: 20, gender: '男' },
{ name: '李四', age: 17, gender: '女' },
{ name: '王五', age: 18, gender: '女' },
{ name: '趙六', age: 22, gender: '男' },
]
const females = persons.filter(person => person.age >= 18 && person.gender === '女')
console.log(females) // [{ name: '王五', age: 18, gender: '女' }]
用filter函數遍歷persons數組,將符合條件的元素放入新的數組females中,並返回females數組。
五、實例二:篩選字元串數組
假設有一個字元串數組,需要篩選出所有以字母a開頭的字元串:
const strs = ['apple', 'banana', 'avocado', 'kiwi', 'apricot']
const aStrs = strs.filter(str => str.startsWith('a'))
console.log(aStrs) // ['apple', 'avocado', 'apricot']
利用filter函數遍歷strs數組,用startsWith方法判斷元素是否以字母a開頭,將符合條件的元素放入新數組aStrs中,最終返回aStrs數組。
六、實例三:篩選數字數組
假設有一個數字數組,需要篩選出所有大於等於70的元素:
const scores = [90, 60, 80, 70, 50, 85]
const highScores = scores.filter(score => score >= 70)
console.log(highScores) // [90, 80, 70, 85]
利用filter函數遍歷scores數組,將大於等於70的元素放入新數組highScores中,並返回highScores數組。
七、結語
Array.filter是一個非常靈活實用的函數,能夠幫助我們快速地從數組中提取所需元素,同時也可以通過自定義回調函數進行更為複雜的篩選操作。希望大家可以善用Array.filter,提高開發效率。
原創文章,作者:UANOQ,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/361062.html