Array.forEach

  • Revision slug: JavaScript/Reference/Global_Objects/Array/forEach
  • Revision title: Array.forEach
  • Revision id: 351063
  • Created:
  • Creator: John Wehin
  • Is current revision? Нет
  • комментировать

Revision Content

Summary

Выполняет функцию один раз для каждого элемента в массиве.

Method of Array
Implemented in JavaScript 1.6
ECMAScript Edition ECMAScript 5th Edition

Синтакс

array.forEach(callback[, thisArg])

Параметры

callback
Функция выполняемая для каждого элемента.
thisArg
Обьект который будет использоваться как this при исполнении функции callback.

Описание

forEach выполняет функцию (callback) один раз для каждого элемента находящегося в массиве. Функция callback будет вызвана только для тех индексов которым присвоенны значения; она не будет вызванна для тех индексов, значения которых были удаленны или значения которым не были присвоенны.

callback будет вызванна с тремя аргументами:

  • значение элемента (value)
  • индекс элемента (index)
  • масси по которому осуществляется обход (array)

If a thisArg parameter is provided to forEach, it will be used as the this value for each callback invocation as if callback.call(thisArg, element, index, array) was called. If thisArg is undefined or null, the this value within the function depends on whether the function is in strict mode or not (passed value if in strict mode, global object if in non-strict mode).

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

Примеры

Печать содержимого в массиве

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

function logArrayElements(element, index, array) {
    console.log("a[" + index + "] = " + element);
}
[2, 5, 9].forEach(logArrayElements);
// logs:
// a[0] = 2
// a[1] = 5
// a[2] = 9

Копирование обьекта

The following code creates a copy of a given object. There are different ways to create a copy of an object. This one is just one of them here to explain how Array.prototype.forEach works. It uses a couple of new ECMAScript 5 Object.* functions.

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

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

  return copy;
}

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

Compatibility

forEach is a recent addition to the ECMA-262 standard; 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 which do not natively support it.

if ( !Array.prototype.forEach ) {
  Array.prototype.forEach = function(fn, scope) {
    for(var i = 0, len = this.length; i < len; ++i) {
      fn.call(scope, this[i], i, this);
    }
  }
}

An algorithm 100% true to the ECMA-262, 5th edition can be seen below:

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.com/#x15.4.4.18
if ( !Array.prototype.forEach ) {

  Array.prototype.forEach = function forEach( 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; // Hack to convert O.length to a UInt32

    // 4. If IsCallable(callback) is false, throw a TypeError exception.
    // See: http://es5.github.com/#x9.11
    if ( {}.toString.call(callback) !== "[object Function]" ) {
      throw new TypeError( callback + " is not a function" );
    }

    // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
    if ( thisArg ) {
      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 ( Object.prototype.hasOwnProperty.call(O, k) ) {

        // 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
  };
}

Browser compatibility

{{ CompatibilityTable() }}

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support {{ CompatVersionUnknown() }} 1.5 9 {{ CompatVersionUnknown() }} {{ CompatVersionUnknown() }}
Feature Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support {{ CompatUnknown() }} {{ CompatUnknown() }} {{ CompatUnknown() }} {{ CompatUnknown() }} {{ CompatUnknown() }}

Based on Kangax's compat tables

Revision Source

<h2 id="Summary">Summary</h2>
<p>Выполняет функцию один раз для каждого элемента в массиве.</p>
<table class="standard-table">
  <thead>
    <tr>
      <th class="header" colspan="2">Method of <a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array" title="JavaScript/Reference/Global_Objects/Array"><code>Array</code></a></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Implemented in</td>
      <td>JavaScript 1.6</td>
    </tr>
    <tr>
      <td>ECMAScript Edition</td>
      <td>ECMAScript 5th Edition</td>
    </tr>
  </tbody>
</table>
<h2 id="Syntax">Синтакс</h2>
<pre class="syntaxbox">
<code><em>array</em>.forEach(<em>callback</em>[, <em>thisArg</em>])</code></pre>
<h3 id="Parameters">Параметры</h3>
<dl>
  <dt>
    <code>callback</code></dt>
  <dd>
    Функция выполняемая для каждого элемента.</dd>
  <dt>
    <code>thisArg</code></dt>
  <dd>
    Обьект который будет использоваться как <code>this</code> при исполнении функции <code>callback</code>.</dd>
</dl>
<h2 id="Description">Описание</h2>
<p><code>forEach</code> выполняет функцию (<code>callback</code>) один раз для каждого элемента находящегося в массиве. <code>Функция callback</code> будет вызвана только для тех индексов которым присвоенны значения; она не будет вызванна для тех индексов, значения которых были удаленны или значения которым не были присвоенны.</p>
<p><code>callback</code> будет вызванна с <strong>тремя аргументами</strong>:</p>
<ul>
  <li>значение элемента<strong> (value)</strong></li>
  <li>индекс элемента<strong> (index)</strong></li>
  <li>масси по которому осуществляется обход <strong>(array)</strong></li>
</ul>
<p>If a <code>thisArg</code> parameter is provided to <code>forEach</code>, it will be used as the <code>this</code> value for each <code>callback</code> invocation as if <code>callback.call(thisArg, element, index, array)</code> was called. If <code>thisArg</code> is <code>undefined</code> or <code>null</code>, the <code>this</code> value within the function depends on whether the function is in <a href="/en-US/docs/JavaScript/Reference/Functions_and_function_scope/Strict_mode" title="JavaScript/Strict_mode">strict mode</a> or not (passed value if in strict mode, global object if in non-strict mode).</p>
<p>The range of elements processed by <code>forEach</code> is set before the first invocation of <code>callback</code>. Elements which are appended to the array after the call to <code>forEach</code> begins will not be visited by <code>callback</code>. If existing elements of the array are changed, or deleted, their value as passed to <code>callback</code> will be the value at the time <code>forEach</code> visits them; elements that are deleted are not visited.</p>
<h2 id="Examples">Примеры</h2>
<h3 id="Printing_the_contents_of_an_array">Печать содержимого в массиве</h3>
<p>The following code logs a line for each element in an array:</p>
<pre class="brush:js">
function logArrayElements(element, index, array) {
    console.log("a[" + index + "] = " + element);
}
[2, 5, 9].forEach(logArrayElements);
// logs:
// a[0] = 2
// a[1] = 5
// a[2] = 9
</pre>
<h3 id="An_object_copy_function">Копирование обьекта</h3>
<p>The following code creates a copy of a given object. There are different ways to create a copy of an object. This one is just one of them here to explain how <code>Array.prototype.forEach</code> works. It uses a couple of new ECMAScript 5 Object.* functions.</p>
<pre class="brush: js">
function copy(o){
  var copy = Object.create( Object.getPrototypeOf(o) );
  var propNames = Object.getOwnPropertyNames(o);

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

  return copy;
}

var o1 = {a:1, b:2};
var o2 = copy(o1); // o2 looks like o1 now
</pre>
<h2 id="Compatibility">Compatibility</h2>
<p><code>forEach</code> is a recent addition to the ECMA-262 standard; 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 <code>forEach</code> in implementations which do not natively support it.</p>
<pre class="brush:js">
if ( !Array.prototype.forEach ) {
  Array.prototype.forEach = function(fn, scope) {
    for(var i = 0, len = this.length; i &lt; len; ++i) {
      fn.call(scope, this[i], i, this);
    }
  }
}
</pre>
<p>An algorithm 100% true to the ECMA-262, 5th edition can be seen below:</p>
<p>This algorithm is exactly the one specified in ECMA-262, 5th edition, assuming <code>Object</code> and <code>TypeError</code> have their original values and that <code>callback.call</code> evaluates to the original value of <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Function/call" title="JavaScript/Reference/Global Objects/Function/call">Function.prototype.call</a></code>.</p>
<!-- DO_NOT_MODIFY_THE_FOLLOWING_CODE_IN_ANY_WAY -->
<pre class="brush: js">
// Production steps of ECMA-262, Edition 5, 15.4.4.18
// Reference: http://es5.github.com/#x15.4.4.18
if ( !Array.prototype.forEach ) {

  Array.prototype.forEach = function forEach( 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 &gt;&gt;&gt; 0; // Hack to convert O.length to a UInt32

    // 4. If IsCallable(callback) is false, throw a TypeError exception.
    // See: http://es5.github.com/#x9.11
    if ( {}.toString.call(callback) !== "[object Function]" ) {
      throw new TypeError( callback + " is not a function" );
    }

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

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

    // 7. Repeat, while k &lt; len
    while( k &lt; 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 ( Object.prototype.hasOwnProperty.call(O, k) ) {

        // 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
  };
}
</pre>
<h2 id="Browser_compatibility">Browser compatibility</h2>
<p>{{ CompatibilityTable() }}</p>
<div id="compat-desktop">
  <table class="compat-table">
    <tbody>
      <tr>
        <th>Feature</th>
        <th>Chrome</th>
        <th>Firefox (Gecko)</th>
        <th>Internet Explorer</th>
        <th>Opera</th>
        <th>Safari</th>
      </tr>
      <tr>
        <td>Basic support</td>
        <td>{{ CompatVersionUnknown() }}</td>
        <td>1.5</td>
        <td>9</td>
        <td>{{ CompatVersionUnknown() }}</td>
        <td>{{ CompatVersionUnknown() }}</td>
      </tr>
    </tbody>
  </table>
</div>
<div id="compat-mobile">
  <table class="compat-table">
    <tbody>
      <tr>
        <th>Feature</th>
        <th>Android</th>
        <th>Firefox Mobile (Gecko)</th>
        <th>IE Mobile</th>
        <th>Opera Mobile</th>
        <th>Safari Mobile</th>
      </tr>
      <tr>
        <td>Basic support</td>
        <td>{{ CompatUnknown() }}</td>
        <td>{{ CompatUnknown() }}</td>
        <td>{{ CompatUnknown() }}</td>
        <td>{{ CompatUnknown() }}</td>
        <td>{{ CompatUnknown() }}</td>
      </tr>
    </tbody>
  </table>
</div>
<p>Based on <a class="external" href="http://kangax.github.com/es5-compat-table/">Kangax's compat tables</a></p>
Revert to this revision