当前位置:网站首页>JS中的filter、map、reduce
JS中的filter、map、reduce
2022-08-10 20:31:00 【Matcha_ice_cream】
1、filter
filter函数会返回一个新数组
filter中的回调函数有一个要求:必须返回一个boolean值
true:当返回true时,函数内部会自动将这次回调的值(n)加入到新数组中
false:当返回false时,函数内部会自动过滤掉这次的值
注意:不会对数组做一些改变,只起到一定的过滤筛选作用。
注意: filter() 不会对空数组进行检测。
代码展示:
let arr = [1, 3, 34, 6,50, 100];
let newArr = arr.filter(function (n) {
return n <= 25;
})
console.log(newArr);
展示效果:
2、map
map函数会返回一个新数组。
map函数在遍历数组的过程中,可以对数组做一些改变,并放到新数组中
参数:可传入三个参数
currentValue:当前元素的值 必须
index:当前元素的索引值 可选
arr:当前元素属于的数组对象 可选
注意:map() 不会对空数组进行检测。
注意:map() 不会改变原始数组。
代码展示:
let arr = [1, 30, 20, 4];
let newArr = arr.map(function (n) {
return n * 2;
})
console.log(newArr);
显示效果:
3、reduce
reduce()方法接收一个函数作为累加器,最终将数组计算为一个值
注意:reduce()对于空数组不会执行回调函数
参数:
total:必需。初始值,或者计算结束后的返回值
currentValue:必需。当前元素
currentIndex:可选。当前元素的索引
arr:可选。当前元素所属的数组
initialValue:可选。传递给函数的初始值
代码展示:
let arr = [10, 20, 40, 80, 100];
let newArr = arr.filter(function (n) {
return n <= 50;
}).map(function (n) {
return n * 2;
}).reduce(function (prevalue, n) {
return prevalue + n;
}, 0)
console.log(newArr);
代码优化:使用箭头函数
let arr2 = [10, 20, 40, 80, 100];
let new2Arr = arr.filter(n => n <= 50).map(n => n * 2).reduce((prev, n) => prev + n , 0);
console.log(new2Arr)
显示效果:
边栏推荐
猜你喜欢
UE4 - 河流流体插件Fluid Flux
OPPO Enco X2 迎来秋季产品升级 旗舰体验全面拉满
转铁蛋白(Tf)修饰去氢骆驼蓬碱磁纳米脂质体/香豆素-6脂质体/多柔比星脂质体
Ferritin particle-loaded raltitrexed/pemetrexed/sulfadesoxine/adamantane (scientific research reagent)
【图像分类】2019-MoblieNetV3 ICCV
Detailed explanation and use of each module of ansible
YOLOv3 SPP source analysis
壁仞推出全球最大算力芯片,号称以7nm超越英伟达4nm最新GPU
win10 xbox录屏功能不能录声音怎么办
线性结构----链表
随机推荐
QSslSocket has not been declared
[SemiDrive source code analysis] [MailBox inter-core communication] 52 - DCF Notify implementation principle analysis and code combat
CGO 初步认知和基本数据类型转换
2021DASCTF实战精英夏令营暨DASCTF July X CBCTF 4th
The evolution history of Go programmers
2021年中国工业互联网安全大赛(福建省选拔赛) 暨首届福建省工业互联网创新大赛
三子棋的设计和代码
Floating window in Auto.js
苹果字体查找
Ferritin particle-loaded raltitrexed/pemetrexed/sulfadesoxine/adamantane (scientific research reagent)
Public Key Retrieval is not allowed(不允许公钥检索)【解决办法】
leetcode 547.省份数量 并查集
echart 特例-多分组X轴
通用线程:POSIX 线程详解,第 2部分
Transferrin-modified osthole long-circulating liposomes/PEG-PLGA nanoparticles loaded with notoginsenoside R1 ([email prot
"POJ 3666" Making the Grade problem solution (two methods)
Common functions of Auto.js to find pictures and colors
C语言详解系列——关于调试那些事
饿了么-机构树单选
面向未来的 IT 基础设施管理架构——融合云(Unified IaaS)