1分钟get ES6 常用函数map、find、set...

常用的map、set、filter、find、findIndex、forEach、reduce处理list的应用整理。

原理什么的可以慢慢看需求来了先码上,2分钟迅速get


map: 从一个列表中获取某个值对应的list

eg:从一个dataListSelections数据中取出列表中每一项的status组成一个新的列表statusList

var statusList = this.dataListSelections.map(item => { console.log(item.status); return item.status; });

set:数组去重

eg:从orgIds中获得没有重复值的orgIdSet

var orgIdSet = new Set(orgIds);

filter:过滤某符合条件的数据

eg:从dataListSelections中过滤得到状态为true的数据enableListSelections

var enableListSelections = this.dataListSelections.filter(item => item.status === true); 


reduce 实现循环相加,acc . (场景:计算 list中某一项的和)

eg:  draftListSelections中所有startQuantity的数量求和赋值给res

let res = draftListSelections.reduce((acc, cur) => { return acc + Number(cur.startQuantity); }, 0);

find 查找一个对象里的元素,找到就返回该元素,找不到返回undefined。

eg :list中查找value 为1 的的元素,查到返回1,找不到返回undefined

let target = list.find(item => item.value === value);

findIndex 查找,找到返回index 找不到返回-1)

var index = list.findIndex((value) => { return value === 1; });

forEach :遍历每一个元素

eg:将selectRightTableData中的所有元素的status改为true

this.selectRightTableData.forEach(item => item.status = true})

最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容