Array.prototype.forEach()

翻譯不完整。請協助 翻譯此英文文件

forEach() ,Array.forEach( )  Array陣列中的每個元素都會被帶入(  )中的callback函式,執行一次。 

語法

arr.forEach(callback[, thisArg])

參數

callback
這個callback函式將會把Array中的每一個元素作為參數,帶進本callback函式裡,每個元素各執行一次,接收三個參數:
currentValue
代表目前被處理中的Array之中的那個元素。
index
代表目前被處理中的Array之中的那個元素的index.
array
呼叫forEach( )方法的那個Array本身,也就是上面Syntax中的arr。
thisArg
可自己選擇要不要作為參數,要寫成this,通常是表示作為呼叫了arr.forEach( )的 "那個物件"。(譯者註:在  Using thisArg 範例中可以看到清楚的解釋)

Description

forEach() executes the provided callback once for each element present in the array in ascending order. It is not invoked for index properties that have been deleted or are uninitialized (i.e. on sparse arrays).

callback is invoked with three arguments:

  • the element value
  • the element index
  • the array being traversed

If a thisArg parameter is provided to forEach(), it will be passed to callback when invoked, for use as its this value.  Otherwise, the value undefined will be passed for use as its this value. The this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function.

The range of elements processed by forEach() is set before the first invocation of callback. Elements that are appended to the array after the call to forEach() begins will not be visited by callback. If the values of existing elements of the array are changed, the value passed to callback will be the value at the time forEach() visits them; elements that are deleted before being visited are not visited.

forEach() executes the callback function once for each array element; unlike map() or reduce() it always returns the value undefined and is not chainable. The typical use case is to execute side effects at the end of a chain.

除非是拋出異常,否則並沒有中止 forEach() 迴圈的辦法。如果你需要這樣做,forEach() 就是錯誤的用法,相反的,應該要用簡單的迴圈。如果你要測試陣列裡面的元素並回傳布林值,可以用 every()some()。如果可以的話,新的方法 find()findIndex() 也可以用於 true 值之後提前終止。

範例

Printing the contents of an array

The following code logs a line for each element in an array:

function logArrayElements(element, index, array) {
  console.log('a[' + index + '] = ' + element);
}

// Notice that index 2 is skipped since there is no item at
// that position in the array.
[2, 5, , 9].forEach(logArrayElements);
// logs:
// a[0] = 2
// a[1] = 5
// a[3] = 9

Using thisArg

以下的這個(有點不自然的)例子示範了如何在一個自定義的Counter物件中,為Counter加上一個叫add的方法(譯者註:注意是Counter.prototype.add ,代表add是一個Counter類別的實體才能用的function,所以這裡才用"方法"來稱呼它),在add方法中,使用到了Array.prototype.forEach,並且將一個陣列作為參數,然後透過這個陣列中的值,將obj這個Counter物件的sum屬性和countg屬性做更新:

(譯者註:在做為參數被傳入forEach()中的callBack裡只有用到entry這個參數,entry就是上面所提到的currentValue,當你只給一個forEach( )一個參數時,預設它就是currentValue)

function Counter() {
  this.sum = 0;
  this.count = 0;
}
Counter.prototype.add = function(array) {
  array.forEach(function(entry) {
    this.sum += entry;
    ++this.count;
  }, this);
  // ^---- 注意這裡
};

var obj = new Counter();
obj.add([2, 5, 9]);
obj.count
// 3 
obj.sum
// 16

注意: 因為thisArg 參數 (this) 有被提供到forEach()函式中,這個this會再被帶入callback函式(5~9行)中被使用。

(譯者註:第9行的this就是第14行的obj,一個在第13行被new出來的Counter物件,所以在array.forEach的callback函式中,我們可以使用這個Counter物件的sum屬性和count屬性,試試看把第2行的0改成其他數字就會很清楚知道譯者在說什麼了...

第5行開始是一個匿名函式,第6行開始又是一個第5行開始的匿名函式中的匿名函式,6~8行的this在這個匿名函式中,如果沒有給thisArg的話,會指向window(而this.sum跟this.count在這種狀況下就是undefined了),因為14行的那個obj的參考傳不進6~8行的這個匿名函式中的匿名函式中,所以才要使用thisArg,才能把外部發動了add()的物件(也就是第14行的obj)參考帶入到add()裡面。)

An object copy function

The following code creates a copy of a given object. There are different ways to create a copy of an object, the following is just one way and is presented to explain how Array.prototype.forEach() works by using ECMAScript 5 Object.* meta property functions.

function copy(obj) {
  var copy = Object.create(Object.getPrototypeOf(obj));
  var propNames = Object.getOwnPropertyNames(obj);

  propNames.forEach(function(name) {
    var desc = Object.getOwnPropertyDescriptor(obj, name);
    Object.defineProperty(copy, name, desc);
  });

  return copy;
}

var obj1 = { a: 1, b: 2 };
var obj2 = copy(obj1); // obj2 looks like obj1 now

Polyfill

forEach() was added to the ECMA-262 standard in the 5th edition; as such it may not be present in other implementations of the standard. You can work around this by inserting the following code at the beginning of your scripts, allowing use of forEach() in implementations that don't natively support it. This algorithm is exactly the one specified in ECMA-262, 5th edition, assuming Object and TypeError have their original values and that callback.call() evaluates to the original value of Function.prototype.call().

// Production steps of ECMA-262, Edition 5, 15.4.4.18
// Reference: http://es5.github.io/#x15.4.4.18
if (!Array.prototype.forEach) {

  Array.prototype.forEach = function(callback, thisArg) {

    var T, k;

    if (this == null) {
      throw new TypeError(' this is null or not defined');
    }

    // 1. Let O be the result of calling toObject() passing the
    // |this| value as the argument.
    var O = Object(this);

    // 2. Let lenValue be the result of calling the Get() internal
    // method of O with the argument "length".
    // 3. Let len be toUint32(lenValue).
    var len = O.length >>> 0;

    // 4. If isCallable(callback) is false, throw a TypeError
    exception. // See: http://es5.github.com/#x9.11
    if (typeof callback !== "function") {
      throw new TypeError(callback + ' is not a function');
    }

    // 5. If thisArg was supplied, let T be thisArg; else let
    // T be undefined.
    if (arguments.length > 1) {
      T = thisArg;
    }

    // 6. Let k be 0
    k = 0;

    // 7. Repeat, while k < len
    while (k < len) {

      var kValue;

      // a. Let Pk be ToString(k).
      //    This is implicit for LHS operands of the in operator
      // b. Let kPresent be the result of calling the HasProperty
      //    internal method of O with argument Pk.
      //    This step can be combined with c
      // c. If kPresent is true, then
      if (k in O) {

        // i. Let kValue be the result of calling the Get internal
        // method of O with argument Pk.
        kValue = O[k];

        // ii. Call the Call internal method of callback with T as
        // the this value and argument list containing kValue, k, and O.
        callback.call(T, kValue, k, O);
      }
      // d. Increase k by 1.
      k++;
    }
    // 8. return undefined
  };
}

Specifications

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

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support (Yes) 1.5 (1.8) 9 (Yes) (Yes)
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support (Yes) (Yes) 1.0 (1.8) (Yes) (Yes) (Yes)

See also

文件標籤與貢獻者

 此頁面的貢獻者: akari0624, iigmir
 最近更新: akari0624,