一、JS數組過濾方法
在js中,數組是一個非常重要的數據類型,它可以存儲多個數據項,並且可以通過下標來訪問每個數據項。在實際應用中,我們常常需要對數組進行篩選,只留下符合條件的數據項。這時候,就需要用到js中的數組過濾方法filter。
數組過濾方法filter的語法如下:
array.filter(callback[, thisArg]);
其中,array是要進行篩選的數組;callback是用於測試每個元素的函數,同時該函數還可以接收三個參數:當前元素、當前元素的索引、原數組。thisArg是可選參數,代表在執行callback函數時使用的this值。該方法將返回一個符合條件的新數組。
二、JS數組過濾對象
在js中,數組的每個元素可以是任意的數據類型,包括對象。如果我們要對一個包含多個對象的數組進行篩選,可以使用filter配合箭頭函數進行操作。
例如,我們有一個包含多個人員信息的數組,我們要篩選出18歲以下的人員信息。代碼如下:
const people = [ {name: "Tom", age: 20}, {name: "Jerry", age: 17}, {name: "John", age: 15}, {name: "Mary", age: 19} ]; const under18s = people.filter(person => person.age < 18); console.log(under18s); // Output: [{name: "Jerry", age: 17}, {name: "John", age: 15}]
三、數組過濾JS
在進行數組過濾時,我們不僅可以使用箭頭函數,還可以使用普通函數來進行篩選。例如,我們有一個包含多個整數的數組,我們要篩選出大於等於10的整數。代碼如下:
const nums = [8, 10, 5, 12, 3]; function filterNum(num) { return num >= 10; } const result = nums.filter(filterNum); console.log(result); // Output: [10, 12]
四、JS數組過濾返回新數組
在使用數組過濾方法filter時,原數組不會發生改變,而是返回一個符合條件的新數組。例如,我們有一個包含多個整數的數組,我們要篩選出大於等於10的整數,並將原數組輸出。代碼如下:
const nums = [8, 10, 5, 12, 3]; function filterNum(num) { return num >= 10; } const result = nums.filter(filterNum); console.log(nums); console.log(result); // Output: [8, 10, 5, 12, 3] // Output: [10, 12]
五、JS數組過濾取值
在使用數組過濾方法filter時,我們不僅可以進行數據篩選,還可以取出符合條件的數據項中的某個值。例如,我們有一個包含多個人員信息的數組,我們要取出18歲以下的人員的姓名。代碼如下:
const people = [ {name: "Tom", age: 20}, {name: "Jerry", age: 17}, {name: "John", age: 15}, {name: "Mary", age: 19} ]; const under18sName = people .filter(person => person.age person.name); console.log(under18sName); // Output: ["Jerry", "John"]
六、JS數組過濾重複
在使用數組過濾方法filter時,我們還可以去重。例如,我們有一個包含多個整數的數組,其中存在重複的元素,我們要去除重複的元素並輸出。代碼如下:
const nums = [1, 2, 3, 4, 3, 2, 1]; const uniqueNums = nums.filter((num, idx, arr) => arr.indexOf(num) === idx); console.log(uniqueNums); // Output: [1, 2, 3, 4]
上面的代碼中,我們通過調用數組方法indexOf來判斷當前元素是否第一次出現,如果是,就將其加入到新數組中。
七、JS數組過濾掉某一項
在使用數組過濾方法filter時,我們還可以將指定的元素從數組中剔除。例如,我們有一個包含多個人員信息的數組,我們要剔除姓名為Jerry的人員信息。代碼如下:
const people = [ {name: "Tom", age: 20}, {name: "Jerry", age: 17}, {name: "John", age: 15}, {name: "Mary", age: 19} ]; const filteredPeople = people.filter(person => person.name !== "Jerry"); console.log(filteredPeople); // Output: [{name: "Tom", age: 20}, {name: "John", age: 15}, {name: "Mary", age: 19}]
八、JS數組過濾空字符串
在進行數組過濾時,我們經常要處理空字符串的情況。例如,我們有一個包含多個字符串的數組,其中某些元素為空字符串,我們要將其過濾掉並輸出。代碼如下:
const strs = ["abc", "", "def", "", "ghi"]; const filteredStrs = strs.filter(str => str !== ""); console.log(filteredStrs); // Output: ["abc", "def", "ghi"]
九、JS數組過濾空值
在進行數組過濾時,我們還要考慮null、undefined等空值的情況。例如,我們有一個包含多個元素的數組,其中某些元素為null或undefined,我們要將其過濾掉並輸出。代碼如下:
const arr = ["abc", null, "def", undefined, "ghi"]; const filteredArr = arr.filter(item => item); console.log(filteredArr); // Output: ["abc", "def", "ghi"]
十、JS數組過濾器選取
JS數組過濾器是一個十分強大的工具,它可以幫助我們從一個數組中選擇滿足特定條件的元素,並返回一個新數組。通過本篇文章,我們了解了JS數組過濾方法的基本語法以及多種應用場景,希望對大家在實際開發中有所幫助。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/153454.html