JS之reduce

以前没接触到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)
发布了30 篇原创文章 · 获赞 8 · 访问量 3万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章