博客
关于我
① 浅谈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/

你可能感兴趣的文章
nginx + etcd 动态负载均衡实践(三)—— 基于nginx-upsync-module实现
查看>>
nginx + etcd 动态负载均衡实践(二)—— 组件安装
查看>>
nginx + etcd 动态负载均衡实践(四)—— 基于confd实现
查看>>
Nginx + Spring Boot 实现负载均衡
查看>>
Nginx + uWSGI + Flask + Vhost
查看>>
Nginx - Header详解
查看>>
Nginx - 反向代理、负载均衡、动静分离、底层原理(案例实战分析)
查看>>
nginx 1.24.0 安装nginx最新稳定版
查看>>
nginx 301 永久重定向
查看>>
nginx css,js合并插件,淘宝nginx合并js,css插件
查看>>
Nginx gateway集群和动态网关
查看>>
Nginx Location配置总结
查看>>
Nginx log文件写入失败?log文件权限设置问题
查看>>
Nginx Lua install
查看>>
nginx net::ERR_ABORTED 403 (Forbidden)
查看>>
Nginx SSL私有证书自签,且反代80端口
查看>>
Nginx upstream性能优化
查看>>
Nginx 中解决跨域问题
查看>>
nginx 代理解决跨域
查看>>
Nginx 动静分离与负载均衡的实现
查看>>