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

你可能感兴趣的文章
npm报错unable to access ‘https://github.com/sohee-lee7/Squire.git/‘
查看>>
npm淘宝镜像过期npm ERR! request to https://registry.npm.taobao.org/vuex failed, reason: certificate has ex
查看>>
npm版本过高问题
查看>>
npm的“--force“和“--legacy-peer-deps“参数
查看>>
npm的安装和更新---npm工作笔记002
查看>>
npm的常用操作---npm工作笔记003
查看>>
npm的常用配置项---npm工作笔记004
查看>>
npm的问题:config global `--global`, `--local` are deprecated. Use `--location=global` instead 的解决办法
查看>>
npm编译报错You may need an additional loader to handle the result of these loaders
查看>>
npm设置淘宝镜像、升级等
查看>>
npm设置源地址,npm官方地址
查看>>
npm设置镜像如淘宝:http://npm.taobao.org/
查看>>
npm配置安装最新淘宝镜像,旧镜像会errror
查看>>
NPM酷库052:sax,按流解析XML
查看>>
npm错误 gyp错误 vs版本不对 msvs_version不兼容
查看>>
npm错误Error: Cannot find module ‘postcss-loader‘
查看>>
npm,yarn,cnpm 的区别
查看>>
NPOI
查看>>
NPOI之Excel——合并单元格、设置样式、输入公式
查看>>
NPOI初级教程
查看>>