一、什麼是arr.filter
arr.filter是JavaScript數組對象的方法之一,它能夠對數組中的元素進行過濾,返回一個新的數組,新數組中包含滿足篩選條件的元素。
二、arr.filter的基本使用方法
arr.filter接受一個回調函數作為參數,該回調函數接受三個參數:當前元素,當前元素的索引,當前數組。
let arr = [1, 2, 3, 4, 5];
let newArr = arr.filter(function(elem, index, arr) {
return elem > 2;
});
console.log(newArr);//[3, 4, 5]
上面的例子中,arr.filter對arr數組中的元素進行了過濾,返回大於2的元素組成的新數組。回調函數返回值為true的元素被包含進新數組中。
三、arr.filter的高級用法
1. 比較函數
arr.filter方法可以接受一個自定義的比較函數,該函數用於決定元素是否應該被保留在新數組中。
let arr = [1, 2, 3, 4, 5];
function even(elem) {
return elem % 2 === 0;
}
let newArr = arr.filter(even);
console.log(newArr);//[2, 4]
上面的例子中,even函數作為回調函數被傳遞給arr.filter,它返回元素是否為偶數的布爾值。
2. 使用箭頭函數簡化代碼
對於簡單的過濾操作,可以使用箭頭函數來簡化代碼。
let arr = [1, 2, 3, 4, 5];
let newArr = arr.filter(elem => elem > 2);
console.log(newArr);//[3, 4, 5]
上面的例子中,使用箭頭函數可以使代碼更加簡潔易讀。
3. 去除重複元素
arr.filter方法可以配合ES6的Set對象實現去除數組中的重複元素。
let arr = [1, 2, 2, 3, 4, 4, 5];
let newArr = [...new Set(arr)];
console.log(newArr);//[1, 2, 3, 4, 5]
上面的例子中,使用Set對象的特性去除arr數組中的重複元素,並使用展開語法將Set對象轉化為數組。
4. 字元串搜索
arr.filter方法可以用於字元串搜索,比如在一個字元串數組中搜索包含特定子串的字元串,並返回符合條件的字元串構成的新數組。
let arr = ['apple', 'banana', 'orange', 'grape', 'cherry'];
let keyword = 'a';
let newArr = arr.filter(function(elem) {
return elem.includes(keyword);
});
console.log(newArr);//['apple', 'banana', 'orange', 'grape']
上面的例子中,使用String對象的includes方法檢查字元串是否包含指定的子串,使用arr.filter過濾符合條件的字元串。
四、小結
通過本文對arr.filter方法的深入講解,我們了解到了arr.filter方法的基本使用方法、高級用法等知識點。對於前端開發來說,熟練掌握arr.filter方法對於提高開發效率非常有幫助。
原創文章,作者:ZBLHO,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/351706.html