您的位置:首页 > Web前端 > JavaScript

JS之reduce

2015-08-18 21:09 671 查看
以前没接触到reduce

忽然遇见了这么个题:

martix = [[1,2],[3,4][5,6]]; var fl = martix.___(function(a,b)____); console.log(fl)//输出[1,2,3,4,5,6]


看看reduce

[0, 1, 2, 3, 4].reduce(function(previousValue, currentValue, index, array) {
return previousValue + currentValue;
});


“MDNreduce”

reduce的callback含四个参数 previousValue, currentValue, index, array

reduce的作用

If initialValue is provided in the call to reduce, then previousValue will be equal to initialValue and currentValue will be equal to the first value in the array. If no initialValue was provided, then previousValue will be equal to the first value in the array and currentValue will be equal to the second.

有初始值,将初始值作为previousValue, 数组第0个值作为currentValue,以此类推

无初始值,将第0个值作为previousValue,数组第1个值作为currentValue,以此类推

现在懂了

martix = [[1,2],[3,4][5,6]]; var fl = martix.reduce(function(a,b){ return a.concat(b);}); console.log(fl)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: