一、Filter函數的介紹
在JavaScript中,數組是一個非常重要的數據類型,屬於對象的一種。在實際的開發過程中,我們往往需要對數組進行篩選、過濾等操作,這時候就可以使用JavaScript中的filter函數。
filter函數是JavaScript中一個很實用的函數,它可以篩選出符合指定條件的數組元素,然後將這些元素組成一個新的數組返回,不影響原來的數組。filter函數的語法如下:
array.filter(function(currentValue,index,arr), thisValue)
其中,參數currentValue表示數組中正在處理的當前元素,index表示當前元素的索引值,arr表示當前數組;而thisValue則可選,表示傳遞給函數的額外值,這個值在函數中使用。
二、Filter函數的基本使用
為了更好的理解filter函數,接下來我們將結合代碼進行詳細的講解。首先,我們定義一個數組:
const arr = [1,2,3,4,5,6,7,8,9];
現在,我們來使用filter函數將這個數組中大於等於5的數篩選出來,並形成一個新的數組:
const result = arr.filter(function(item){ return item >= 5; }); console.log(result); // [5,6,7,8,9]
我們還可以使用箭頭函數進行簡寫:
const result = arr.filter(item => item >= 5); console.log(result); // [5,6,7,8,9]
三、Filter函數進階使用
1. 字元串的篩選
在使用filter函數中,我們不僅可以對數字進行篩選,還可以對字元串進行篩選。比如下面這個例子,我們來對一個字元串數組進行篩選,只要包含字母e的字元串:
const strArr = ['hello', 'world', 'apple', 'pear', 'peach']; const result = strArr.filter(function(item){ return item.indexOf('e') >= 0; }); console.log(result); // ["hello", "pear", "peach"]
2. 對象的篩選
除了對數組和字元串進行篩選,我們還可以對對象進行篩選。比如下面這個例子,我們有一個存儲人員信息的數組,我們來篩選出工資大於等於5000的人員:
const staff = [ {name: 'Bob', salary: 4000}, {name: 'Alice', salary: 6000}, {name: 'John', salary: 5000}, {name: 'Tom', salary: 7000} ]; const result = staff.filter(function(item){ return item.salary >= 5000; }); console.log(result); // [{name: 'Alice', salary: 6000},{name: 'John', salary: 5000},{name: 'Tom', salary: 7000}]
3. 複雜條件篩選
除了基本的條件篩選,我們還可以使用filter函數進行更加複雜的篩選操作。比如下面這個例子,我們要將一個數值數組按照奇數和偶數分別存儲到兩個數組中:
const arr = [1,2,3,4,5,6,7,8,9]; const result = { odd:[], even:[] }; arr.filter(function(item){ if(item%2 === 0){ result.even.push(item); }else{ result.odd.push(item); } }); console.log(result); // {odd: [1, 3, 5, 7, 9], even: [2, 4, 6, 8]}
四、總結
通過本文的介紹和實例演示,我們了解了JavaScript中的filter函數的基本語法和用法,並能夠熟練的運用到我們的開發工作中。同時,我們也發現filter函數不僅可以應用於數組篩選上,還可以應用到字元串和對象等其他數據類型上,功能非常強大。
原創文章,作者:TLMO,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/135409.html