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

开发 前端
数组非常适合存储相关数据,并且通常用作组织信息的一种方式。 我们中的大多数人每天都在使用它们,但是您知道 JavaScript 中还内置了一些非常简洁的数组方法吗?

介绍

数组非常适合存储相关数据,并且通常用作组织信息的一种方式。 我们中的大多数人每天都在使用它们,但是您知道 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);
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
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"
  },
]
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.

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)
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
arrayOfAges: [25, 30, 21]
  • 1.

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);
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
depositsArray: [{...}, {...}, {...}, {...}, {...}]
sumOfDeposits: 55
  • 1.
  • 2.

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)
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
isNotValidUsers: true
  • 1.

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);
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
hasStock: true
  • 1.

结论

数组是任何编程语言中最基本和最重要的数据结构之一。 在学习 JavaScript 时,了解如何使用这些数组方法更有效地操作和存储数据会很有帮助。 这些方法包括 filter()、map()、reduce()、some() 和 every(),它们可以帮助您提高代码效率。

责任编辑:华轩 来源: 七爪网
相关推荐

2020-03-19 15:30:08

JavaScript数组字符串

2022-09-27 14:36:57

JavaScrip数组开发

2022-04-28 08:41:53

JavaScript数组

2023-07-04 15:52:49

JavaScript数组

2023-06-02 15:53:38

工具Python开发

2024-10-11 13:17:16

Linux命令行快捷导航

2023-06-29 15:08:21

JavaScrip开发

2022-11-07 16:25:07

JavaScript技巧

2023-02-06 16:46:59

JavaScript程序员技巧

2015-07-23 10:37:13

Linux命令

2022-08-10 12:02:52

面试JavaScript

2022-11-13 15:33:30

JavaScript数组开发

2011-05-11 15:28:05

2020-07-20 08:40:42

转型

2024-07-29 07:00:00

JavaScript字符串数组对象

2024-09-18 15:58:05

2012-09-29 10:29:56

.Net内存分配继承

2012-09-29 09:22:24

.NETGC内存分配

2017-12-07 15:28:36

2020-02-28 14:05:00

Linuxshell命令
点赞
收藏

51CTO技术栈公众号