以前沒接觸到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)