aboutsummaryrefslogtreecommitdiff
path: root/files/de/web/javascript/reference/global_objects/array/foreach/index.html
blob: faba9795cb482cad5d5dd0bbce1219ddc45d3c35 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
---
title: Array.prototype.forEach()
slug: Web/JavaScript/Reference/Global_Objects/Array/forEach
tags:
  - Array
  - ECMAScript 5
  - JavaScript
  - Method
  - Prototype
  - Reference
translation_of: Web/JavaScript/Reference/Global_Objects/Array/forEach
---
<div>{{JSRef}}</div>

<p>Die <code><strong>forEach()</strong></code> Methode führt eine übergebene Funktion für jedes Element eines Arrays aus.</p>

<div>{{EmbedInteractiveExample("pages/js/array-foreach.html")}}</div>



<p><span class="comment token">// a</span> <span class="comment token">// b</span> <span class="comment token">// c</span></p>

<h2 id="Syntax" name="Syntax">Syntax</h2>

<pre class="syntaxbox"><var>arr</var>.forEach(function <var>callback(currentValue [, index [, array]]) {
    // Ihr Iterator
}</var>[, <var>thisArg</var>]);</pre>

<h3 id="Parameters" name="Parameters">Parameter</h3>

<dl>
 <dt><code>callback</code></dt>
 <dd>Funktion, die auf jedes Element angewendet wird mit drei Argumenten:</dd>
 <dd>
 <dl>
  <dt><code>currentValue</code></dt>
  <dd>Der Wert des aktuellen Elements im Array.</dd>
  <dt><code>index</code> {{optional_inline}}</dt>
  <dd>Der Index des aktuellen Elements im Array.</dd>
  <dt><code>array</code> {{optional_inline}}</dt>
  <dd>Das Array, welches mit <code>forEach()</code> durlaufen wird.</dd>
 </dl>
 </dd>
 <dt><code>thisArg</code> {{optional_inline}}</dt>
 <dd>Wert der als <code>this</code> verwendet wird, wenn <code>callback</code> ausgeführt wird.</dd>
 <dt> </dt>
</dl>

<h3 id="Rückgabewert">Rückgabewert</h3>

<p>{{jsxref("undefined")}}.</p>

<h2 id="Description" name="Description">Beschreibung</h2>

<p><code>forEach()</code> ruft eine bereitgestellte <code>callback</code>-Funktion einmal für jedes Element in einem Array in aufsteigender Reihenfolge auf. Sie wird nicht für Elemente aufgerufen, die gelöscht oder nicht initialisiert wurden (d. h. Arrays mit leeren Elementen).</p>

<p><code>callback</code> wird mit drei Argumenten aufgerufen:</p>

<ol>
 <li>Der Wert des Elements</li>
 <li>Der Index des Elements</li>
 <li>Das Array-Objekt, das durchlaufen wird</li>
</ol>

<p>Falls der Parameter <code>thisArg</code> an <code>forEach()</code> übergeben wird, wird er als Wert für <code>this</code> innerhalb von <code>callback</code> verwendet. Andernfalls hat <code>this</code> den Wert {{jsxref("undefined")}}. Welchen Wert <code>callback</code> letztendlich in <code>this</code> sieht wird gemäß <a href="/de/docs/Web/JavaScript/Reference/Operators/this">der üblichen Regeln bestimmt, nach denen <code>this</code> für eine Funktion ermittelt wird</a>.</p>

<p><code>forEach()</code> selbst verändert das Array nicht, auf dem es aufgerufen wird (das aufgerufene <code>callback</code> kann jedoch Änderungen vornehmen).</p>

<p>Der Bereich der von <code>forEach()</code> verarbeiteten Elemente wird vor dem ersten Aufruf von <code>callback</code> festgelegt. Elemente, die nach Beginn des Aufrufs von <code>forEach()</code> an das Array angehängt werden, werden von <code>callback</code> nicht berücksichtigt. Wenn vorhandene Elemente des Arrays geändert werden, ist der Wert maßgeblich, den <code>forEach()</code> beim Erreichen eines Elements antrifft und dann an <code>callback</code> übergibt. Nachfolgende Elemente, die nach Beginn eines Durchlaufs von <code>forEach()</code> gelöscht werden (z. B. durch {{jsxref("Array.prototype.shift()", "shift()")}}), bevor sie eingelesen werden konnten, werden nicht mehr berücksichtigt (siehe Beispiel unten).</p>

<p><code>forEach()</code> führt <code>callback</code> einmal für jedes Element im Array aus; im Gegensatz zu {{jsxref("Array.prototype.map()", "map()")}} oder {{jsxref("Array.prototype.reduce()", "reduce()")}} gibt es immer den Wert {{jsxref("undefined")}} zurück und ist nicht verknüpfbar. Der typische Anwendungsfall ist das Ausführen von Nebenwirkungen am Ende einer einer solchen Kette.</p>

<div class="note">
<p>Es gibt keine Möglichkeit eine <code>forEach()</code>-Schleife zu unterbrechen oder zu verlassen, außer durch das erzeugen einer Exception. Wird eine solche Möglichkeit jedoch benötigt, stellt <code>forEach()</code> das falsche Mittel dar.</p>

<p>Vorzeitiges Verlassen ist verfügbar in:</p>

<ul>
 <li>Einer einfachen Schleife</li>
 <li>Einer {{jsxref("statements/for...of", "for...of")}} Schleife</li>
 <li>{{jsxref("Array.prototype.every()")}}</li>
 <li>{{jsxref("Array.prototype.some()")}}</li>
 <li>{{jsxref("Array.prototype.find()")}}</li>
 <li>{{jsxref("Array.prototype.findIndex()")}}</li>
</ul>

<p>Die anderen Array Methoden {{jsxref("Array.prototype.every()", "every()")}}{{jsxref("Array.prototype.some()", "some()")}}{{jsxref("Array.prototype.find()", "find()")}} und {{jsxref("Array.prototype.findIndex()", "findIndex()")}} prüfen die Elemente im Array auf eine Bedingung, die einen {{Glossary("Truthy")}}-Wert zurückgibt mit dem bestimmt wird, ob weitere Durchläufe nötig sind.</p>
</div>

<h2 id="Examples" name="Examples">Beispiele</h2>

<h3 id="forEach()_statt_einer_for-Schleife"><code>forEach()</code> statt einer for-Schleife</h3>

<pre class="brush: js">const items = ['item1', 'item2', 'item3'];
const copy = [];

// Vorher
for (let i=0; i&lt;items.length; i++) {
  copy.push(items[i]);
}

// Nachher
items.forEach(function(item){
  copy.push(item);
});</pre>

<h3 id="Example:_Printing_the_contents_of_an_array" name="Example:_Printing_the_contents_of_an_array">Inhalte eines Arrays ausgeben</h3>

<div class="blockIndicator note">
<p><strong>Hinweis:</strong> Um den Inhalt eines Arrays vorformatiert auf der Konsole auszugeben können Sie auch {{jsxref("console.table()")}} verwenden. Dieses Beispiel zeigt eine weitere Möglichkeit mittels <code>forEach()</code>.</p>
</div>

<p>Der folgende Code gibt eine Zeile pro Element des Arrays aus:</p>

<pre class="brush:js">function logArrayElements(element, index, array) {
  console.log('a[' + index + '] = ' + element);
}

// Hinweis zur Auslassung: Es gibt keinen Eintrag mit dem Index 2
// somit wird dieser übersprungen
[2, 5, , 9].forEach(logArrayElements);
// Ausgabe:
// a[0] = 2
// a[1] = 5
// a[3] = 9
</pre>

<h3 id="Verwendung_von_thisArg">Verwendung von <code>thisArg</code></h3>

<p>Das folgende (fingierte) Beispiel aktualisiert die Eigenschaften eines Objekts eines jeden Eintrags im Array:</p>

<pre class="brush:js line-numbers  language-js"><code class="language-js"><span class="keyword token">function</span> <span class="function token">Counter</span><span class="punctuation token">(</span><span class="punctuation token">)</span> <span class="punctuation token">{</span>
  <span class="keyword token">this</span><span class="punctuation token">.</span>sum <span class="operator token">=</span> <span class="number token">0</span><span class="punctuation token">;</span>
  <span class="keyword token">this</span><span class="punctuation token">.</span>count <span class="operator token">=</span> <span class="number token">0</span><span class="punctuation token">;</span>
<span class="punctuation token">}</span>
Counter<span class="punctuation token">.</span>prototype<span class="punctuation token">.</span>add <span class="operator token">=</span> <span class="keyword token">function</span><span class="punctuation token">(</span>array<span class="punctuation token">)</span> <span class="punctuation token">{</span>
  array<span class="punctuation token">.</span><span class="function token">forEach</span><span class="punctuation token">(</span><span class="keyword token">function</span><span class="punctuation token">(</span>entry<span class="punctuation token">)</span> <span class="punctuation token">{</span>
    <span class="keyword token">this</span><span class="punctuation token">.</span>sum <span class="operator token">+</span><span class="operator token">=</span> entry<span class="punctuation token">;</span>
    <span class="operator token">++</span><span class="keyword token">this</span><span class="punctuation token">.</span>count<span class="punctuation token">;</span>
  <span class="punctuation token">}</span><span class="punctuation token">,</span> <span class="keyword token">this</span><span class="punctuation token">)</span><span class="punctuation token">;</span>
  <span class="comment token">// ^---- Beachten</span>
<span class="punctuation token">}</span><span class="punctuation token">;</span>

<span class="keyword token">var</span> obj <span class="operator token">=</span> <span class="keyword token">new</span> <span class="class-name token">Counter</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">;</span>
obj<span class="punctuation token">.</span><span class="function token">add</span><span class="punctuation token">(</span><span class="punctuation token">[</span><span class="number token">2</span><span class="punctuation token">,</span> <span class="number token">5</span><span class="punctuation token">,</span> <span class="number token">9</span><span class="punctuation token">]</span><span class="punctuation token">)</span><span class="punctuation token">;</span>
obj<span class="punctuation token">.</span>count<span class="punctuation token">;</span>
<span class="comment token">// 3 </span>
obj<span class="punctuation token">.</span>sum<span class="punctuation token">;</span>
<span class="comment token">// 16</span></code></pre>

<p>Da <code>forEach()</code> der Parameter <code>thisArg</code> (<code>this</code>) zur Verfügung steht, wird er bei jedem Aufruf an <code>callback</code> weitergegeben, um es als seinen <code>this</code>-Wert zu benutzen.</p>

<div class="note">
<p>Wenn das Funktionsargument durch die <a href="/de/docs/Web/JavaScript/Reference/Functions/Pfeilfunktionen">Pfeilnotation</a> angegeben wird, kann der Parameter <code>thisArg</code> weggelassen werden, da Pfeilfunktionen den {{jsxref("Operators/this", "this")}}-Wert lexikalisch vermerken.</p>
</div>

<h3 id="Example:_An_object_copy_function" name="Example:_An_object_copy_function">Funktion zum Kopieren eines Objekts</h3>

<p>Der folgende Code erzeugt eine Kopie des übergebenen Objekts. Es gibt verschiedene Möglichkeiten, ein Objekt zu kopieren. Die Folgende ist nur eine davon und dient zur Veranschaulichung, wie <code>Array.prototype.forEach()</code> funktioniert, indem ECMAScript 5 <code>Object.*</code> Meta-Funktionen genutzt werden.</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 sieht jetzt aus wie o1</pre>

<h3 id="Wird_das_Array_während_des_Durchlaufes_modifiziert_könnten_andere_Elemente_übersprungen_werden.">Wird das Array während des Durchlaufes modifiziert, könnten andere Elemente übersprungen werden.</h3>

<p>Das folgende Beispiel protokolliert "eins", "zwei", "vier". Wenn der Eintrag mit dem Wert "zwei" erreicht ist, wird der erste Eintrag des Arrays mit {{jsxref("Array.prototype.shift()", "shift()")}} entfernt, was dazu führt, dass alle übrigen Einträge um eine Position aufrücken. Weil Element "vier" jetzt an einer früheren Position im Array ist, wird "drei" übersprungen. <code>forEach()</code> erzeugt keine Kopie des Arrays vor dem Durchlauf.</p>

<pre class="brush:js line-numbers  language-js"><code class="language-js"><span class="keyword token">var</span> words <span class="operator token">=</span> <span class="punctuation token">[</span><span class="string token">'eins'</span><span class="punctuation token">,</span> <span class="string token">'zwei'</span><span class="punctuation token">,</span> <span class="string token">'drei'</span><span class="punctuation token">,</span> <span class="string token">'vier'</span><span class="punctuation token">]</span><span class="punctuation token">;</span>
words<span class="punctuation token">.</span><span class="function token">forEach</span><span class="punctuation token">(</span><span class="keyword token">function</span><span class="punctuation token">(</span>word<span class="punctuation token">)</span> <span class="punctuation token">{</span>
  console<span class="punctuation token">.</span><span class="function token">log</span><span class="punctuation token">(</span>word<span class="punctuation token">)</span><span class="punctuation token">;</span>
  <span class="keyword token">if</span> <span class="punctuation token">(</span>word <span class="operator token">===</span> <span class="string token">'zwei'</span><span class="punctuation token">)</span> <span class="punctuation token">{</span>
    words<span class="punctuation token">.</span><span class="function token">shift</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">;</span>
  <span class="punctuation token">}</span>
<span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span>
<span class="comment token">// eins</span>
<span class="comment token">// zwei</span>
<span class="comment token">// vier</span></code></pre>

<h2 id="Polyfill" name="Polyfill">Polyfill</h2>

<p><code>forEach()</code> wurde dem ECMA-262-Standard in der 5. Auflage hinzugefügt. Als solches ist es möglicherweise nicht in allen Implementierungen des Standards enthalten. Sie können dies umgehen, indem Sie den folgenden Code am Anfang Ihrer Skripte einfügen, um die Verwendung von <code>forEach()</code> in Implementierungen zu ermöglichen, die es nicht nativ unterstützen. Dieser Algorithmus entspricht dem in der 5. Auflage von ECMA-262 angegebenen Algorithmus, vorausgesetzt {{jsxref("Object")}} und {{jsxref("TypeError")}} haben ihre ursprünglichen Werte und <code>callback.call()</code> wird mit dem ursprünglichen Wert von {{jsxref("Function.prototype.call")}} ausgewertet.</p>

<pre class="brush: js">// 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 &gt;&gt;&gt; 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 &gt; 1) {
      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 (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
  };
}
</pre>

<h2 id="Specifications" name="Specifications">Spezifikationen</h2>

<table class="standard-table">
 <thead>
  <tr>
   <th scope="col">Spezifikation</th>
   <th scope="col">Status</th>
   <th scope="col">Kommentar</th>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td>{{SpecName('ES5.1', '#sec-15.4.4.18', 'Array.prototype.forEach')}}</td>
   <td>{{Spec2('ES5.1')}}</td>
   <td>Initiale Definition. Implementiert in JavaScript 1.6.</td>
  </tr>
  <tr>
   <td>{{SpecName('ES6', '#sec-array.prototype.foreach', 'Array.prototype.forEach')}}</td>
   <td>{{Spec2('ES6')}}</td>
   <td> </td>
  </tr>
  <tr>
   <td>{{SpecName('ESDraft', '#sec-array.prototype.foreach', 'Array.prototype.forEach')}}</td>
   <td>{{Spec2('ESDraft')}}</td>
   <td> </td>
  </tr>
 </tbody>
</table>

<h2 id="Browser_compatibility" name="Browser_compatibility">Browser-Kompatibilität</h2>

<div>


<p>{{Compat("javascript.builtins.Array.forEach")}}</p>
</div>

<h2 id="See_also" name="See_also">Siehe auch</h2>

<ul>
 <li>{{jsxref("Array.prototype.find()")}}</li>
 <li>{{jsxref("Array.prototype.findIndex()")}}</li>
 <li>{{jsxref("Array.prototype.map()")}}</li>
 <li>{{jsxref("Array.prototype.filter()")}}</li>
 <li>{{jsxref("Array.prototype.every()")}}</li>
 <li>{{jsxref("Array.prototype.some()")}}</li>
 <li>{{jsxref("Map.prototype.forEach()")}}</li>
 <li>{{jsxref("Set.prototype.forEach()")}}</li>
</ul>