1. 程式人生 > 其它 >JavaScript 中 陣列的 reduce() 方法用法

JavaScript 中 陣列的 reduce() 方法用法

  1. 語法

    array.reduce(callback, [initValue])
    

    reduce為陣列中每個元素依次呼叫callback函式,不包括陣列中未賦值或刪除的元素

    // 第一個引數,callback 接收四個引數
    function(total, currentValue, index, array){
        // 必須,用於執行每個陣列元素的函式
    }
    // 回撥引數解釋
    total: 			// 必須,提供的初始值(initValue),或者上一次呼叫回撥返回的值
    currentValue:	// 必須,陣列中當前要被處理的元素
    index:			// 可選,當前元素在陣列中的索引
    array:			// 可選,呼叫reduce的陣列
    // 第二個引數
    initValue		// 可選,作為第一次呼叫 callback 的第一個引數
    
  2. 例項解析 initValue 引數

    第一個例子:

    var array = [1, 2, 3, 4];
    var sum = array.reduce(function(total, currentValue, index, array) {
        console.log(total, currentValue, index);
        return total + currentValue;
    });
    console.log(array, sum);
    

    執行結果:

    1 2 1
    3 3 2
    6 4 3
    [1, 2, 3, 4] 10

    從執行結果可以看出,index是從 1 開始的,第一次 total 的值是 array 的第一個值。陣列長度是4,但是reduce函式迴圈了3次。

    第二個例子:

    var array = [1, 2, 3, 4];
    var sum = array.reduce(function(total, currentValue, index, array) {
        console.log(total, currentValue, index);
        return total + currentValue;
    }, 0);	// 注意:這裡設定了 initValue 值 0
    console.log(array, sum);
    

    執行結果:

    0 1 0
    1 2 1
    3 3 2
    6 4 3
    [1, 2, 3, 4] 10

    這裡 index 是從 0 開始的,第一次 total 的值是我們設定的 initValue

    的值 0 , 陣列長度是 4 ,reduce 迴圈了 4 次。

    結論:如果不設定 initValue 的值,reduce 會從索引1的地方開始執行 callback 方法,跳過第一個索引。如果設定 initialValue 的值,從索引0開始。

    需要注意的是,如果 array 是一個空陣列,這時候呼叫 reduce 沒有設定 initValue 會報錯,所以呼叫 reduce 函式時,設定 initValue 更安全。

  3. 簡單用法

    陣列求和求乘積

    var array = [1, 2, 3, 4];
    var sum = array.reduce(function(total, currentValue){
        return total + currentValue
    });
    var mul = array.reduce(function(total, currentValue){
        return total * currentValue
    });
    console.log(sum);	// 10
    console.log(mul);	// 24