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
|
---
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><code><strong>forEach()</strong></code> 方法會將陣列內的每個元素,皆傳入並執行給定的函式一次。</p>
<div>{{EmbedInteractiveExample("pages/js/array-foreach.html")}}</div>
<h2 id="語法">語法</h2>
<pre class="syntaxbox"><var>arr</var>.forEach(function <var>callback(currentValue[, index[, array]]) {
//your iterator
}</var>[, <var>thisArg</var>]);</pre>
<h3 id="參數">參數</h3>
<dl>
<dt><code>callback</code></dt>
<dd>這個 callback 函式將會把 Array 中的每一個元素作為參數,帶進本 callback 函式裡,每個元素各執行一次,接收三個參數:
<dl>
<dt><code>currentValue</code></dt>
<dd>代表目前被處理中的 Array 之中的那個元素。</dd>
<dt><code>index</code>{{optional_inline}}</dt>
<dd>代表目前被處理中的 Array 之中的那個元素的index.</dd>
<dt><code>array</code>{{optional_inline}}</dt>
<dd>呼叫 <code>forEach()</code> 方法的那個 Array 本身,也就是上面語法中的 arr。</dd>
</dl>
</dd>
<dt><code>thisArg</code> {{Optional_inline}}</dt>
<dd>執行 <code>callback</code> 回呼函式的 <code><strong>this</strong></code>(即參考之 <code>Object</code>)值。</dd>
</dl>
<h3 id="回傳值">回傳值</h3>
<p>{{jsxref("undefined")}}。</p>
<h2 id="描述">描述</h2>
<p><code>forEach()</code> executes the provided <code>callback</code> 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).</p>
<p><code>callback</code> is invoked with <strong>three arguments</strong>:</p>
<ul>
<li>the <strong>element value</strong></li>
<li>the <strong>element index</strong></li>
<li>the <strong>array being traversed</strong></li>
</ul>
<p>If a <code>thisArg</code> parameter is provided to <code>forEach()</code>, it will be used as callback's <code>this</code> value. Otherwise, the value {{jsxref("undefined")}} will be used as its <code>this</code> value. The <code>this</code> value ultimately observable by <code>callback</code> is determined according to <a href="/zh-TW/docs/Web/JavaScript/Reference/Operators/this">the usual rules for determining the <code>this</code> seen by a function</a>.</p>
<p>The range of elements processed by <code>forEach()</code> is set before the first invocation of <code>callback</code>. Elements that are appended to the array after the call to <code>forEach()</code> begins will not be visited by <code>callback</code>. If the values of existing elements of the array are changed, the value passed to <code>callback</code> will be the value at the time <code>forEach()</code> visits them; elements that are deleted before being visited are not visited. If elements that are already visited are removed (e.g. using {{jsxref("Array.prototype.shift()", "shift()")}}) during the iteration, later elements will be skipped - see example below.</p>
<p><code>forEach()</code> executes the <code>callback</code> function once for each array element; unlike {{jsxref("Array.prototype.map()", "map()")}} or {{jsxref("Array.prototype.reduce()", "reduce()")}} it always returns the value {{jsxref("undefined")}} and is not chainable. The typical use case is to execute side effects at the end of a chain.</p>
<p><code>forEach()</code> does not mutate the array on which it is called (although <code>callback</code>, if invoked, may do so).</p>
<div class="notecard note">
<p><strong>備註:</strong>除非是拋出異常,否則並沒有中止 <code>forEach()</code> 迴圈的辦法。如果你需要這樣做,<code>forEach()</code> 就是錯誤的用法,相反的,應該要用簡單的迴圈。如果你要測試陣列裡面的元素並回傳布林值,可以用 {{jsxref("Array.prototype.every()", "every()")}} 或 {{jsxref("Array.prototype.some()", "some()")}}。如果可以的話,新的方法 {{jsxref("Array.prototype.find()", "find()")}} 或 {{jsxref("Array.prototype.findIndex()", "findIndex()")}} 也可以用於 true 值之後提前終止。</p>
</div>
<h2 id="範例">範例</h2>
<h3 id="Converting_from_for_to_forEach">Converting from for to forEach</h3>
<p>before</p>
<pre class="brush:js">const items = ['item1', 'item2', 'item3'];
const copy = [];
for (let i=0; i<items.length; i++) {
copy.push(items[i])
}
</pre>
<p>after</p>
<pre class="brush:js">const items = ['item1', 'item2', 'item3'];
const copy = [];
items.forEach(function(item){
copy.push(item)
});
</pre>
<p> </p>
<h3 id="Printing_the_contents_of_an_array">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);
}
// 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
</pre>
<h3 id="Using_thisArg">Using <code>thisArg</code></h3>
<p>The following (contrived) example updates an object's properties from each entry in the array:</p>
<pre class="brush:js">function Counter() {
this.sum = 0;
this.count = 0;
}
Counter.prototype.add = function(array) {
array.forEach(function(entry) {
this.sum += entry;
++this.count;
}, this);
// ^---- Note
};
const obj = new Counter();
obj.add([2, 5, 9]);
obj.count;
// 3
obj.sum;
// 16
</pre>
<p>Since the <code>thisArg</code> parameter (<code>this</code>) is provided to <code>forEach()</code>, it is passed to <code>callback</code> each time it's invoked, for use as its <code>this</code> value.</p>
<div class="notecard note">
<p><strong>Note:</strong> If passing the function argument using an <a href="/zh-TW/docs/Web/JavaScript/Reference/Functions/Arrow_functions">arrow function expression</a> the <code>thisArg</code> parameter can be omitted as arrow functions lexically bind the {{jsxref("Operators/this", "this")}} value.</p>
</div>
<h3 id="An_object_copy_function">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; the following is just one way and is presented to explain how <code>Array.prototype.forEach()</code> works by using ECMAScript 5 <code>Object.*</code> meta property functions.</p>
<pre class="brush: js">function copy(obj) {
const copy = Object.create(Object.getPrototypeOf(obj));
const propNames = Object.getOwnPropertyNames(obj);
propNames.forEach(function(name) {
const desc = Object.getOwnPropertyDescriptor(obj, name);
Object.defineProperty(copy, name, desc);
});
return copy;
}
const obj1 = { a: 1, b: 2 };
const obj2 = copy(obj1); // obj2 looks like obj1 now
</pre>
<h3 id="If_the_array_is_modified_during_iteration_other_elements_might_be_skipped.">If the array is modified during iteration, other elements might be skipped.</h3>
<p>The following example logs "one", "two", "four". When the entry containing the value "two" is reached, the first entry of the whole array is shifted off, which results in all remaining entries moving up one position. Because element "four" is now at an earlier position in the array, "three" will be skipped. <code>forEach()</code> does not make a copy of the array before iterating.</p>
<pre class="brush:js">var words = ['one', 'two', 'three', 'four'];
words.forEach(function(word) {
console.log(word);
if (word === 'two') {
words.shift();
}
});
// one
// two
// four
</pre>
<h2 id="Polyfill">Polyfill</h2>
<p><code>forEach()</code> 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 <code>forEach()</code> in implementations that don't natively support it. This algorithm is exactly the one specified in ECMA-262, 5th edition, assuming {{jsxref("Object")}} and {{jsxref("TypeError")}} have their original values and that <code>callback.call()</code> evaluates to the original value of {{jsxref("Function.prototype.call()")}}.</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 >>> 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 = arguments[1];
}
// 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.
};
}
</pre>
<h2 id="規範">規範</h2>
<table class="standard-table">
<tbody>
<tr>
<th scope="col">Specification</th>
<th scope="col">Status</th>
<th scope="col">Comment</th>
</tr>
<tr>
<td>{{SpecName('ES5.1', '#sec-15.4.4.18', 'Array.prototype.forEach')}}</td>
<td>{{Spec2('ES5.1')}}</td>
<td>Initial definition. Implemented 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="瀏覽器相容性">瀏覽器相容性</h2>
<div>
<p>{{Compat("javascript.builtins.Array.forEach")}}</p>
</div>
<h2 id="參見">參見</h2>
<ul>
<li>{{jsxref("Array.prototype.find()")}}</li>
<li>{{jsxref("Array.prototype.findIndex()")}}</li>
<li>{{jsxref("Array.prototype.map()")}}</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>
|