Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

此文件需要技術審查。看看您能幫什麼忙。

我們的志工尚未將此文章翻譯為 正體中文 (繁體) 版本。加入我們,幫忙翻譯!

The reduce() method applies a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value.

Syntax

arr.reduce(callback[, initialValue])

Parameters

callback
Function to execute on each value in the array, taking four arguments:
previousValue
The value previously returned in the last invocation of the callback, or initialValue, if supplied. (See below.)
currentValue
The current element being processed in the array.
currentIndex
The index of the current element being processed in the array. Starts at index 0, if an initialValue is provided, and at index 1 otherwise.
array
The array reduce was called upon.
initialValue
Optional. Value to use as the first argument to the first call of the callback.

Return value

The value that results from the reduction.

Description

reduce executes the callback function once for each element present in the array, excluding holes in the array, receiving four arguments:

  • previousValue
  • currentValue
  • currentIndex
  • array

The first time the callback is called, previousValue and currentValue can be one of two values. 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.

Note: If initialValue isn't provided, reduce will execute the callback function starting at index 1, skipping the first index. If initialValue is provided, it will start at index 0.

If the array is empty and no initialValue was provided, TypeError would be thrown. If the array has only one element (regardless of position) and no initialValue was provided, or if initialValue is provided but the array is empty, the solo value would be returned without calling callback.

It is usually safer to provide an initial value because there are three possible outputs without initialValue, as shown in the following example.

var maxCallback = ( pre, cur ) => Math.max( pre.x, cur.x );
var maxCallback2 = ( max, cur ) => Math.max( max, cur );

// reduce() without initialValue
[ { x: 22 }, { x: 42 } ].reduce( maxCallback ); // 42
[ { x: 22 }            ].reduce( maxCallback ); // { x: 22 }
[                      ].reduce( maxCallback ); // TypeError

// map/reduce; better solution, also works for empty arrays
[ { x: 22 }, { x: 42 } ].map( el => el.x )
                        .reduce( maxCallback2, -Infinity );

How reduce works

Suppose the following use of reduce occurred:

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

The callback would be invoked four times, with the arguments and return values in each call being as follows:

  previousValue currentValue currentIndex array return value
first call 0 1 1 [0, 1, 2, 3, 4] 1
second call 1 2 2 [0, 1, 2, 3, 4] 3
third call 3 3 3 [0, 1, 2, 3, 4] 6
fourth call 6 4 4 [0, 1, 2, 3, 4] 10

The value returned by reduce would be that of the last callback invocation (10).

You can also provide an Arrow Function in lieu of a full function. The code below will produce the same output as the code in the block above:

[0, 1, 2, 3, 4].reduce( (prev, curr) => prev + curr );

If you were to provide an initial value as the second argument to reduce, the result would look like this:

[0,1,2,3,4].reduce( (previousValue, currentValue, currentIndex, array) => {
  return previousValue + currentValue;
}, 10);
  previousValue currentValue currentIndex array return value
first call 10 0 0 [0, 1, 2, 3, 4] 10
second call 10 1 1 [0, 1, 2, 3, 4] 11
third call 11 2 2 [0, 1, 2, 3, 4] 13
fourth call 13 3 3 [0, 1, 2, 3, 4] 16
fifth call 16 4 4 [0, 1, 2, 3, 4] 20

The final call return value (20) is returned as a result of the reduce function

Examples

Sum all the values of an array

var total = [0, 1, 2, 3].reduce(function(a, b) {
  return a + b;
}, 0);
// total == 6

Alternatively, written with an arrow function:

var total = [ 0, 1, 2, 3 ].reduce( ( acc, cur ) => acc + cur, 0 );

Flatten an array of arrays

var flattened = [[0, 1], [2, 3], [4, 5]].reduce(function(a, b) {
  return a.concat(b);
}, []);
// flattened is [0, 1, 2, 3, 4, 5]

Bonding arrays contained in the array of objects using spread operator and initialValue

// friends - an array of objects 
// where object field "books" - list of favorite books 
var friends = [ 
{ name: "Anna", books: ["Bible", "Harry Potter"], age: 21 }, 
{ name: "Bob", books: ["War and peace", "Romeo and Juliet"], age: 26 },
{ name: "Alice", books: ["The Lord of the Rings", "The Shining"], age: 18 }
]

// allbooks - list which will contain all friends books +  
// additional list contained in initialValue
var allbooks = friends.reduce(function(prev, curr) {
  return [...prev, ...curr.books];
}, ["Alphabet"]);

// allbooks = ["Alphabet", "Bible", "Harry Potter", "War and peace", 
// "Romeo and Juliet", "The Lord of the Rings", "The Shining"]

Polyfill

Array.prototype.reduce was added to the ECMA-262 standard in the 5th edition; as such it may not be present in all implementations of the standard. You can work around this by inserting the following code at the beginning of your scripts, allowing use of reduce in implementations which do not natively support it.

// Production steps of ECMA-262, Edition 5, 15.4.4.21
// Reference: https://es5.github.io/#x15.4.4.21
if (!Array.prototype.reduce) {
  Array.prototype.reduce = function(callback /*, initialValue*/) {
    'use strict';
    if (this === null) {
      throw new TypeError('Array.prototype.reduce called on null or undefined');
    }
    if (typeof callback !== 'function') {
      throw new TypeError(callback + ' is not a function');
    }
    var t = Object(this), len = t.length >>> 0, k = 0, value;
    if (arguments.length == 2) {
      value = arguments[1];
    } else {
      while (k < len && !(k in t)) {
        k++; 
      }
      if (k >= len) {
        throw new TypeError('Reduce of empty array with no initial value');
      }
      value = t[k++];
    }
    for (; k < len; k++) {
      if (k in t) {
        value = callback(value, t[k], k, t);
      }
    }
    return value;
  };
}

Specifications

Specification Status Comment
ECMAScript 5.1 (ECMA-262)
The definition of 'Array.prototype.reduce' in that specification.
Standard Initial definition. Implemented in JavaScript 1.8.
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'Array.prototype.reduce' in that specification.
Standard  
ECMAScript 2017 Draft (ECMA-262)
The definition of 'Array.prototype.reduce' in that specification.
Draft  

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support (Yes) 3.0 (1.9) 9 10.5 4.0
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support (Yes) (Yes) (Yes) (Yes) (Yes) (Yes)

See also