介紹
數組非常适合存儲相關資料,并且通常用作組織資訊的一種方式。 我們中的大多數人每天都在使用它們,但是您知道 JavaScript 中還内置了一些非常簡潔的數組方法嗎?
這些方法使我們的生活變得更加輕松,将多行代碼優化為一個簡單的指令。 無論您是剛開始使用數組還是已經感覺自己是專家,本文都将幫助您在使用它們時變得更有效率。
filter()
如果您想根據特定條件過濾數組,您可能需要 filter() 方法。 這是一個有用的函數,它将傳回一個包含您感興趣的所有項目的新數組。
它需要一個函數作為參數,它将為數組中的每個元素調用。 如果函數傳回 true,則該元素将保留在數組中; 否則,它将從數組中删除。
例子
我們已從後端請求資料,并希望根據對象數組具有的屬性進行用戶端過濾。 在這種情況下,我們已從 JokeAPI 請求笑話,并希望過濾類别屬性等于 Programming 的笑話。
const response = {
"error": false,
"amount": 4,
"jokes": [
{
"category": "Programming",
"type": "single",
"joke": "Judge: \"I sentence you to the maximum punishment...\"\nMe (thinking): \"Please be death, please be death...\"\nJudge: \"Learn Java!\"\nMe: \"Damn.\"",
"id": 45,
"safe": true,
"lang": "en"
},
{
"category": "Christmas",
"type": "twopart",
"setup": "How will Christmas dinner be different after Brexit?",
"delivery": "No Brussels!",
"id": 251,
"safe": false,
"lang": "en"
},
{
"category": "Christmas",
"type": "twopart",
"setup": "What do Santa's little helpers learn at school?",
"delivery": "The elf-abet!\n",
"id": 248,
"safe": true,
"lang": "en"
},
{
"category": "Christmas",
"type": "twopart",
"setup": "Why couldn't the skeleton go to the Christmas party?",
"delivery": "Because he had no body to go with!",
"id": 252,
"safe": true,
"lang": "en"
}
]
}
const programmingJokes = response.jokes.filter((joke) =>
joke.category === "Programming"
);
console.log("programmingJokes: ", programmingJokes);
programmingJokes: [
{
"category": "Programming",
"type": "single",
"joke": "Judge: \"I sentence you to the maximum punishment...\"\nMe (thinking): \"Please be death, please be death...\"\nJudge: \"Learn Java!\"\nMe: \"Damn.\"",
"id": 45,
"safe": true,
"lang": "en"
},
]
map()
map() 方法轉換數組中的每一項,對其應用一個函數并将結果存儲在一個新數組中,而不實際更改初始數組。
例子
我們已從後端請求資料,并希望從該資料中提取資訊。 在這種情況下,我們從 RandomDataAPI 請求随機使用者資料,并希望将每個人的年齡提取到一個數組中。
const response = [
{
"id": 7433,
"uid": "4c2c1731-2c3c-4983-b39f-0f988791e98f",
"password": "L903JpXGAj",
"first_name": "Dalene",
"last_name": "Kuhn",
"username": "dalene.kuhn",
"email": "[email protected]",
"avatar": "https://robohash.org/autmagnisunt.png?size=300x300&set=set1",
"gender": "Agender",
"phone_number": "+964 771-857-9446 x77784",
"social_insurance_number": "607847845",
"age": 25,
},
{
"id": 3764,
"uid": "0c1c9485-2b90-4e68-a795-0e4925aa8344",
"password": "XjyI92Y1dl",
"first_name": "Laurence",
"last_name": "Lowe",
"username": "laurence.lowe",
"email": "[email protected]",
"avatar": "https://robohash.org/quinonomnis.png?size=300x300&set=set1",
"gender": "Agender",
"phone_number": "+689 743-128-5476 x530",
"social_insurance_number": "737935460",
"age": 30,
},
{
"id": 9408,
"uid": "4933cb5d-f4f5-4bc3-8d37-f4c9b3129923",
"password": "JrI8e4KVjs",
"first_name": "Gabriella",
"last_name": "Tillman",
"username": "gabriella.tillman",
"email": "[email protected]",
"avatar": "https://robohash.org/repellatmaioresmolestiae.png?size=300x300&set=set1",
"gender": "Bigender",
"phone_number": "+675 552-834-4168 x39534",
"age": 21,
}
]
const arrayOfAges = response.map(person => person.age);
console.log("arrayOfAges: ", arrayOfAges)
arrayOfAges: [25, 30, 21]
reduce()
reduce() 方法通過對每個元素應用一個函數并累積結果,将數組縮減為單個值。 這是查找總數或查找所有項目平均值的好方法。
例子
我們有一個包含每月存款的數組,我們想知道所有存款的總和。
const depositsArray = [
{
id: 1231,
deposit: 5,
currency: '#39;,
},
{
id: 1231,
deposit: 10,
currency: '#39;,
},
{
id: 1231,
deposit: 20,
currency: '#39;,
},
{
id: 1231,
deposit: 5,
currency: '#39;,
},
{
id: 1231,
deposit: 15,
currency: '#39;,
},
];
const sumOfDeposits = depositsArray.reduce((total, transaction) =>
total + transaction.deposit, 0
);
console.log('depositsArray: ', depositsArray);
console.log('sumOfDeposits: ', sumOfDeposits);
depositsArray: [{...}, {...}, {...}, {...}, {...}]
sumOfDeposits: 55
some()
some() 方法檢查數組中的至少一個元素是否滿足由提供的函數實作的測試。 如果它确實滿足測試,它将傳回true; 否則,它将傳回 false。
例子
我們已從後端請求使用者,并想知道其中一個是否已被标記為機器人。
const response = [
{
id: 101,
firstName: 'Muhammad',
lastName: 'Ovi',
age: 25,
isBot: false,
},
{
id: 102,
firstName: 'John',
lastName: 'Doe',
age: 30,
isBot: true,
},
{
id: 103,
firstName: 'Chris',
lastName: 'Smith',
age: 27,
isBot: false,
},
];
const isNotValidUsers = response.some((user) => user.isBot === false);
console.log("isNotValidUsers: ", isNotValidUsers)
isNotValidUsers: true
every()
every() 方法檢查數組中的每個元素是否滿足由提供的函數實作的測試。 如果是,它将傳回 true; 否則,它将傳回 false
例子
我們的購物車中有一份産品清單,想檢查是否有庫存。
const response = [
{
"id": 1,
"title": "iPhone 9",
"price": 549,
"discountPercentage": 12.96,
"rating": 4.69,
"stock": 94
},
{
"id": 2,
"title": "Apple Watch",
"price": 300,
"discountPercentage": 10,
"rating": 4.40,
"stock": 20
},
{
"id": 3,
"title": "Apple Headphones",
"price": 600,
"discountPercentage": 7,
"rating": 4.65,
"stock": 2
},
]
const hasStock = response.every((item) => item.stock > 0);
console.log("hasStock: ", hasStock);
hasStock: true
結論
數組是任何程式設計語言中最基本和最重要的資料結構之一。 在學習 JavaScript 時,了解如何使用這些數組方法更有效地操作和存儲資料會很有幫助。 這些方法包括 filter()、map()、reduce()、some() 和 every(),它們可以幫助您提高代碼效率。
關注七爪網,擷取更多APP/小程式/網站源碼資源!