首页>国内 > 正文

五个必须知道的 JavaScript 数组方法,让你的生活更轻松

2022-10-18 17:06:22来源:七爪网

介绍

数组非常适合存储相关数据,并且通常用作组织信息的一种方式。 我们中的大多数人每天都在使用它们,但是您知道 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": "dalene.kuhn@email.com",    "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": "laurence.lowe@email.com",    "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": "gabriella.tillman@email.com",    "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: "$",},{      id: 1231,      deposit: 10,      currency: "$",},{      id: 1231,      deposit: 20,      currency: "$",},{      id: 1231,      deposit: 5,      currency: "$",},{      id: 1231,         deposit: 15,         currency: "$",},];  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(),它们可以帮助您提高代码效率。

关键词: 函数实现 感觉自己 这是一个 代码优化

相关新闻

Copyright 2015-2020   三好网  版权所有 联系邮箱:435 22 640@qq.com  备案号: 京ICP备2022022245号-21