本文共 1707 字,大约阅读时间需要 5 分钟。
作为开发者,我们经常需要对数组数据进行操作,如过滤、映射、查找和归约等。以下是一些常用的数组方法及其使用方法,帮助你更高效地处理数据。
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]
forEach方法forEach方法对数组中的每个元素执行一个函数,但不会返回新数组。
array.forEach(function(currentValue, index, arr), thisValue);
break; 结束循环。代码示例:
let numbers = [4, 9, 16, 25];(numbers.forEach((item, idx) => { console.log(`数组第 ${idx} 位的值是 ${item}`);})); 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]
find方法find方法用于查找数组中第一个满足条件的元素。
array.find(function(currentValue, index, arr), thisValue);
undefined。代码示例:
let numbers = [1, 2, 3];numbers.find(num => num >= 2); // 返回 2
findIndex方法findIndex方法返回数组中第一个满足条件的元素的索引。
array.findIndex(function(currentValue, index, arr), thisValue);
-1。代码示例:
let ages = [3, 10, 19, 20];ages.findIndex(age => age >= 18); // 返回 2
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/