歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> JavaScript數組方法reduce解析

JavaScript數組方法reduce解析

日期:2017/3/1 9:08:12   编辑:Linux編程

Array.prototype.reduce()

概述

reduce()方法是數組的一個實例方法(共有方法),可以被數組的實例對象調用。reduce() 方法接收一個函數作為累加器(accumulator),數組中的每個值(從左到右)開始縮減,最終為一個值。

語法

arr.reduce(callback[, initialValue]) {}

參數

回調函數中可以傳遞四個參數。

previousValue:上一次調用回調函數返回的值,或者是提供的初始值(initialValue)

currentValue:數組中當前被處理的元素

currentIndex:當前被處理元素在數組中的索引, 即currentValue的索引.如果有initialValue初始值, 從0開始.如果沒有從1開始

array:調用 reduce 的數組

initialValue:可選參數, 作為第一次調用 callback 的第一個參數

返回值

reduce()返回值是最後一次調用回調函數返回的結果

描述

reduce 為數組中的每一個元素依次執行回調函數,不包括數組中被刪除或從未被賦值的元素,接受四個參數:

  • previousValu 上一次值
  • currentValue 當前值
  • currentIndex 當前值的索引
  • array 數組

回調函數第一次執行時,previousValue 和 currentValue可能是兩個不同值其中的一個,如果reduce有initialValue參數,那麼 previousValue 等於 initialValue ,並且currentValue 等於數組中的第一個值;如果reduce沒有 initialValue 參數,那麼previousValue 等於數組中的第一個值,currentValue等於數組中的第二個值。

注意: 如果沒有initialValue參數, reduce從index為1開始執行回調函數, 跳過第一個index。 如果有initialValue參數, reduce 將從index為 0 開始執行回調

如果數組是空的並且沒有initialValue參數, 將會拋出TypeError錯誤. 如果數組只有一個元素並且沒有初始值initialValue, 或者有initialValue但數組是空的, 這個唯一的值直接被返回而不會調用回調函數。

通常來說提供一個initialValue初始值更安全一點, 因為沒有的話會出現如下輸出結果。

//沒有提供initialValue
function foo(){
    return [1,2,3,4,5].reduce((x, y) => x + y);   //15
};
console.log(foo.call(this));

function foo(){
    return [].reduce((x, y) => x + y);   //TypeError
};
console.log(foo.call(this));

//提供initialValue
function foo(){
    return [].reduce((x, y) => x + y, 0);   //0
};
console.log(foo.call(this));

reduce()是如何工作的

[0, 1, 2, 3, 4].reduce((previousValue, currentValue, index, array) => previousValue + currentValue);

回調被執行四次,每次的參數和返回值如下表:

reduce 的返回值是回調函數最後一次被調用的返回值(10)。

如果把初始值作為第二個參數傳入 reduce,結果如下,結果如下:

[0, 1, 2, 3, 4].reduce((previousValue, currentValue, index, array) => previousValue + currentValue, 10);


最後一次函數調用的返回值 (20) 作為reduce函數的結果被返回

注意:添加了initialValue參數會多調用一次回調函數

例題

將數組所有項相加

let sum = [0, 1, 2, 3, 4].reduce((x, y) => x + y, 0);  
// 10

扁平化一個二維數組

let arr = [[1, 2], [3, 4], [5, 6]].reduce((x, y) => x.concat(y), []);
// [1, 2, 3, 4, 5, 6]

Copyright © Linux教程網 All Rights Reserved