js中常用的高阶函数
Published on Jan 09, 2023, with 37 view(s) and 0 comment(s)
Ai 摘要:本文介绍了JavaScript中五种常用的高阶函数:filter(筛选符合条件的元素组成新数组)、map(对数组元素处理后返回新数组)、reduce(累加或统计数组元素)、find(返回第一个符合条件的元素值)和findIndex(返回第一个符合条件的元素索引)。这些函数以其他函数作为参数或返回值,能高效处理数组操作,并通过代码示例展示了其用法和效果。

1,filter

作用:创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。  语法:array.filter(function(currentValue,index,arr), thisValue)  返回值:符合条件的元素组成的新数组

let nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let newNums = nums.filter((item, index, arr) => {
  return item % 2 === 0;
});
console.log(newNums); // [ 2, 4, 6, 8, 10 ]
console.log(nums); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

2,map

作用:返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。  语法:array.map(function(currentValue,index,arr), thisValue)  返回值:一个新数组

let nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let newNums = nums.map((item, index, arr) => {
  return item * 2;
});
console.log(newNums);
// [2,  4,  6,  8, 10, 12, 14, 16, 18, 20]

3,reduce

作用:统计,累加  语法:array.reduce(function(total, currentValue, currentIndex, arr), initialValue)     total:必需。初始值,或者结束后的返回值     currentValue:必需。当前元素     currentIndex:可选,当前元素索引     arr:可选,当前元素所属的数组对象     initialValue:可选,传递给函数的初始值  返回值:累计结果

let nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let newNums = nums.reduce((total, item, index, arr) => {
  return total + item;
});
console.log(newNums); //55

4,find

作用: 方法返回通过测试(函数内判断)的数组的第一个元素的值。  语法:array.find(function(currentValue, index, arr),thisValue)  返回值:返回符合测试条件的第一个数组元素值,如果没有符合条件的则返回 undefined。

let nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let newNums = nums.find((item, index, arr) => {
  return item === 3;
});
console.log(newNums); // 3

5,findIndex

语法:和find类似,返回值为第一个符合条件元素的索引值

let nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let newNums = nums.findIndex((item, index, arr) => {
  return item === 3;
});
console.log(newNums); // 2