js中常用的高阶函数

原文链接:js中常用的高阶函数 (sunjianxiang.cn)

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值