Array.reduce
是干吗的?
用于累计计算
举个例子
比如说把这个数组计算累计值
[11, 22, 33, 44, 55]
用forEach
怎么实现?
let xiaoming = [11,22,33,44,55];
let result = 0;
xiaoming.forEach((val,index) => {
result += val;
});
这种方式有什么问题?
需要额外定义 result
那能不能不定义 result
?
可以,用 reduce
那么用reduce
应该怎么写?
不知道
reduce
需要几个参数?
2个,分别是,reducer
和 initialValue
reducer
做什么的?
不知道
累加器
它有几个参数?
4个,分别是: memo
, currentVal
, currentIndex
, arr
memo
是做什么的?
存上一次累加计算的结果
那第一次遍历的时候memo
是什么?
就 initialValue
下一次呢?
currentVal
+ memo
只能是 +
?
不一定,比如,各种四则运算
reducer
中 currentVal
累加完成以后,memo
怎么处理?
return memo
为什么要 return memo
?
給下一次遍历用,作为新的 memo
例子:[['a', 11], ['b', 22], ['c', 33]] ==> {a: 11, b: 22, c: 33}
怎么用 reduce 实现?
let xiaohong = [['a', 11], ['b', 22], ['c', 33]];
let xiaoming = xiaohong.reduce((memo, curVal, curIdx, arr) => {
memo[curVal[0]] = curVal[1];
return memo;
}, {});
更高级的例子: ['http://baidu.com/api1.json', 'http://baidu.com/api2.json', 'http://baidu.com/api3.json']
实现顺序请求?
let xiaobai = ['http://baidu.com/api1.json', 'http://baidu.com/api2.json', 'http://baidu.com/api3.json'];
let xiaohei = xiaobai.reduce((memo, curVal, curIdx, arr) => {
return memo.then(() => {
console.log('request', curVal);
});
}, Promise.resolve(1));
xiaohei.then(()=>{console.log('done')});
为什么看结果是xiaohei.then()
?
下一篇继续我问我答!!!
该文章由 IAsk 生成