博客
关于我
① 浅谈JS的Array对象方法
阅读量:670 次
发布时间:2019-03-16

本文共 1699 字,大约阅读时间需要 5 分钟。

JavaScript数组常用方法详解

作为开发者,我们经常需要对数组数据进行操作,如过滤、映射、查找和归约等。以下是一些常用的数组方法及其使用方法,帮助你更高效地处理数据。


1. map方法

map方法用于对数组中的每个元素执行一个函数,返回一个新数组。每个元素处理后的值会组成新的数组。

语法

array.map(function(currentValue, index, arr), thisValue);

参数说明

  • function:必需参数,作为处理函数。
    • currentValue:当前数组元素的值,默认为必需参数。
    • index:当前数组元素的索引,可选。
    • arr:当前数组,可选。
示例 说明
numbers.map(sqrt) 使用内建函数 Math.sqrt 进行映射。

代码示例

let ages = [32, 33, 12, 40];ages.map(age => age * age); // 返回平方后的新数组:[1024, 1089, 144, 1600]

2. forEach方法

forEach方法对数组中的每个元素执行一个函数,但不会返回新数组。

语法

array.forEach(function(currentValue, index, arr), thisValue);

功能

  • 逐个遍历数组元素。
  • 可用 break; 结束循环。

代码示例

let numbers = [4, 9, 16, 25];(numbers.forEach((item, idx) => {  console.log(`数组第 ${idx} 位的值是 ${item}`);}));

3. filter方法

filter方法用于筛选数组,保留符合条件的元素,返回一个新数组。

语法

array.filter(function(currentValue, index, arr), thisValue);

参数说明

  • function:处理函数,返回 true 的元素保留,false 的元素筛选出去。

代码示例

let ages = [32, 33, 12, 40];ages.filter(age => age >= 18); // 返回 [32, 33, 40]

4. find方法

find方法用于查找数组中第一个满足条件的元素。

语法

array.find(function(currentValue, index, arr), thisValue);

返回值

  • 当找到符合条件的元素时,返回该元素;
  • 如果未找到,返回 undefined

代码示例

let numbers = [1, 2, 3];numbers.find(num => num >= 2); // 返回 2

5. findIndex方法

findIndex方法返回数组中第一个满足条件的元素的索引。

语法

array.findIndex(function(currentValue, index, arr), thisValue);

返回值

  • 索引号符合条件时返回,否则返回 -1

代码示例

let ages = [3, 10, 19, 20];ages.findIndex(age => age >= 18); // 返回 2

6. reduce方法

reduce方法用于将数组中的元素依次归约为一个值。

语法

array.reduce(function(total, currentValue, index, arr), initialValue);

参数说明

  • function:累加器函数。
    • total:累加器初始值或之前归约结果。
    • currentValue:当前元素的值。
    • index:当前元素的索引。
    • arr:当前数组。

代码示例

var numbers = [1, 2, 3, 4];numbers.reduce((sum, num) => sum + num); // 返回 10

通过合理运用这些方法,你可以对数组数据进行更高级的操作,提升代码的简洁性和可读性。

转载地址:http://bzaqz.baihongyu.com/

你可能感兴趣的文章
Prometheus pushgateway使用详解
查看>>
Prometheus 云原生 - Prometheus 数据模型、Metrics 指标类型、Exporter 相关
查看>>
Prometheus 云原生 - 基于 file_sd、http_sd 实现 Service Discovery
查看>>
Prometheus 云原生 - 微服务监控报警系统 (Promethus、Grafana、Node_Exporter)部署、简单使用
查看>>
Prometheus 云原生 - 监控 Linux、MySQL、Redis、RabbitMQ、Docker、SpringBoot 3.x
查看>>
Prometheus 介绍
查看>>
Prometheus 安全配置详解
查看>>
prometheus 安装node_exporter, node_exporter 安装最新版 普罗米修思安装监控服务器client
查看>>
Prometheus 安装部署实战
查看>>
prometheus 持久化存储方案
查看>>
Prometheus 监控系统企业级实战
查看>>
Prometheus 监控系统简介
查看>>
Prometheus 配置详解
查看>>
Prometheus 采集器使用详解
查看>>
Prometheus 黑盒监控实战
查看>>
prometheus+alertmanager+grafana监控部署教程
查看>>
Prometheus+Grafana构建智能化Kubernetes监控系统实战
查看>>
Prometheus+SpringBoot应用监控全过程详解
查看>>
Prometheus+SpringBoot应用监控全过程详解
查看>>
prometheus安装
查看>>