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

你可能感兴趣的文章
oracle ogg 单实例双向复制搭建(oracle-oracle)--Oracle GoldenGate
查看>>
Oracle ora-12514报错解决方法
查看>>
oracle ORA-14402 OGG-01296
查看>>
oracle package包头和package body包体例子
查看>>
oracle partition by list,深入解析partition-list 分区
查看>>
Oracle PL/SQL Dev工具(破解版)被植入勒索病毒的安全预警及自查通告
查看>>
oracle pl/sql 导出用户表结构
查看>>
Oracle PLSQL Demo - 17.游标查询个别字段(非整表)
查看>>
oracle rac 安装 PRVG-13606 ntp 同步报错解决过程
查看>>
Oracle RAC性能调整的方案
查看>>
oracle rac集群的东西之QQ聊天
查看>>
UML— 用例图
查看>>
Oracle Schema Objects——Tables——Table Compression
查看>>
oracle scott趣事
查看>>
oracle script
查看>>
Oracle select表要带双引号的原因
查看>>
Oracle SOA Suit Adapter
查看>>
Oracle Spatial GeoRaster 金字塔栅格存储
查看>>
Oracle spatial 周边查询SQL
查看>>
Oracle Spatial空间数据库建立
查看>>