JS函数式编程 数组部分风格 ES6版
遍历数组:
for(let item of array) {
}
// FP
// return array
array.map((item, index) => {})查找数组中的一项:
for(let item of array) {
if(item === _item) {
}
}
// FP
// return item 匹配条件的第一项
array.find(item => item === _item)数组过滤:
for(let item of array) {
if(item > someValue) {
}
}
// FP
// return array
array.filter(item => item > someValue)reduce
reduce() 方法接收一个函数作为累加器,数组中的每个值从左到右开始执行方法,最终返回一个值。
array.reduce((preValue, currentValue, index, array) => {}, initialValue);
// fn(fn(fn(initialValue, array[0]), array[1]), array[2])
// 假如array = [1, 2, 3]
// 执行
array.reduce((preValue, currentValue) => preValue + currentValue, 0);
// 执行过程为
// step 1. return 0 + 1
// step 2. return 1 + 2
// step 3. return 3 + 3求和:
let array = [1, 2, 3, 4, 5];
let sum = 0;
for(let item of array) {
sum += item;
}
// FP
let sum = array.reduce((pre, cur) => pre + cur, 0);复杂应用:
// 将'/aaa/bbb/ccc' 解析为 ['/aaa', '/aaa/bbb', '/aaa/bbb/ccc']
const fn = path =>
path.split('/')
.map(item => '/' + item)
.reduce((pre, cur, index) => pre.concat(index < 1 ? '' : pre[index - 1] + cur), [])
.filter((item, index) => index > 0);更多文章 yjy5264.github.io
相关推荐
Jruing 2020-11-01
89231645 2020-10-26
87204154 2020-09-24
81244053 2020-09-23
FalseNotFalse 2020-09-22
81540398 2020-09-04
84423067 2020-06-12
hongbing 2020-06-02
huavhuahua 2020-05-11
samsai00 2020-05-06
猛禽的编程艺术 2020-04-23
上海滩 2020-04-22
斑点喵 2020-03-04
cuiguanjun 2020-03-01
TheBigBlue 2020-02-20
banzhihuanyu 2020-02-19
banzhihuanyu 2020-02-15
89510196 2020-02-06
banzhihuanyu 2020-01-31