diff options
Diffstat (limited to 'files/vi/web/javascript/reference/global_objects/array/foreach')
| -rw-r--r-- | files/vi/web/javascript/reference/global_objects/array/foreach/index.html | 303 |
1 files changed, 303 insertions, 0 deletions
diff --git a/files/vi/web/javascript/reference/global_objects/array/foreach/index.html b/files/vi/web/javascript/reference/global_objects/array/foreach/index.html new file mode 100644 index 0000000000..6121f40a83 --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/array/foreach/index.html @@ -0,0 +1,303 @@ +--- +title: Array.prototype.forEach() +slug: Web/JavaScript/Reference/Global_Objects/Array/forEach +translation_of: Web/JavaScript/Reference/Global_Objects/Array/forEach +--- +<div>{{JSRef}}</div> + +<p>Phương thức <code><strong>forEach()</strong></code> sẽ thực thi một hàm khi duyệt qua từng phần tử của mảng.</p> + +<div>{{EmbedInteractiveExample("pages/js/array-foreach.html")}}</div> + + + +<h2 id="Cú_pháp">Cú pháp</h2> + +<pre class="syntaxbox"><var>arr</var>.forEach(function <var>callback(currentValue[, index[, array]]) { + //your iterator +}</var>[, <var>thisArg</var>]);</pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>callback</code></dt> + <dd>Hàm sẽ thực thi lên từng phần tử của mảng được gọi, hàm này nhận 3 tham số: + <dl> + <dt><code>currentValue</code>{{optional_inline}}</dt> + <dd>Giá trị của phần tử đang được duyệt.</dd> + <dt><code>index</code>{{optional_inline}}</dt> + <dd>Chỉ mục của phần tử đang được duyệt.</dd> + <dt><code>array</code>{{optional_inline}}</dt> + <dd>Mảng mà hàm <code>forEach()</code> đang duyệt.</dd> + </dl> + </dd> + <dt><code>thisArg</code> {{Optional_inline}}</dt> + <dd> + <p>Giá trị được gán cho từ khóa <code><strong>this</strong></code> bên trong hàm <code>callback</code> khi được thực thi.</p> + </dd> +</dl> + +<h3 id="Giá_trị_trả_về">Giá trị trả về</h3> + +<p>{{jsxref("undefined")}}.</p> + +<h2 id="Mô_tả_chi_tiết">Mô tả chi tiết</h2> + +<p><code>forEach()</code> thực thi hàm <code>callback</code> trong lúc duyệt tới từng phần tử của mảng theo thứ tự tăng dần. Nó sẽ không được gọi cho vị trí index đã bị xóa hoặc không được khởi tạo (đối với mảng thưa - sparse arrays).</p> + +<p><code>callback</code> được gọi với <strong>3 tham số</strong>:</p> + +<ul> + <li><strong>giá trị của phần tử</strong></li> + <li><strong>index của phần tử</strong></li> + <li><strong>mảng đang được duyệt </strong></li> +</ul> + +<p>Nếu tham số <code>thisArg</code> được truyền vào cho <code>forEach()</code>, nó sẽ được dùng cho từ khóa <code>this</code> trong hàm callback. Nếu không, giá trị {{jsxref("undefined")}} sẽ được dùng cho từ khóa <code>this</code>. Tóm lại, giá trị của từ khóa <code>this</code> trong hàm <code>callback</code> được xác định tuân theo <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this">các quy tắc thông thường để xác định <code>this</code> trong một hàm</a>.</p> + +<p>Khoảng các phần tử được xử lý bởi <code>forEach()</code> được thiết lập trước lần gọi đầu tiên của <code>callback</code>. Phần tử được thêm vào mảng sau khi gọi <code>forEach()</code> sẽ không được <code>callback</code> bắt gặp. Nếu giá trị của các phần tử sẵn có trong mảng thay đổi, thì giá trị truyền vào <code>callback</code> sẽ là giá trị lúc <code>forEach()</code> gặp chúng; phần tử bị xoá trước khi bắt gặp sẽ không tính. Nếu phần tử đã gặp rồi bị loại đi (ví dụ dùng {{jsxref("Array.prototype.shift()", "shift()")}}) trong quá trình lặp, các phần tử sau sẽ bị bỏ qua - xem ví dụ phía dưới.</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="note"> +<p>Khác với cú pháp lặp truyền thống, không có cách nào để ngừng vòng lặp forEach ngoài việc ném ra một ngoại lệ. Nếu vì một mục đích nào đó mà bạn cần ngừng vòng lặp thì nên dùng cách khác thay vì dùng forEach</p> + +<p>Một số cách có thể dùng trong trường hợp đó:</p> + +<ul> + <li>Vòng lặp <a href="https://wiki.developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for">for</a> đơn giản</li> + <li>Vòng lặp <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of">for...of</a> </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>Một số hàm khác trên kiểu mảng: {{jsxref("Array.prototype.every()", "every()")}}, {{jsxref("Array.prototype.some()", "some()")}}, {{jsxref("Array.prototype.find()", "find()")}}, and {{jsxref("Array.prototype.findIndex()", "findIndex()")}} test the array elements with a predicate returning a truthy value to determine if further iteration is required.</p> +</div> + +<h2 id="Ví_dụ">Ví dụ</h2> + +<h3 id="Converting_a_for_loop_to_forEach">Converting a for loop 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> + +<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="note"> +<p>If passing the function argument using an <a href="/en-US/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="Đặc_tả">Đặc tả</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="Trình_duyệt_tương_thích">Trình duyệt tương thích</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.forEach")}}</p> +</div> + +<h2 id="Xem_thêm">Xem thêm</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> |
