diff options
author | Ryan Johnson <rjohnson@mozilla.com> | 2021-04-29 16:16:42 -0700 |
---|---|---|
committer | GitHub <noreply@github.com> | 2021-04-29 16:16:42 -0700 |
commit | 95aca4b4d8fa62815d4bd412fff1a364f842814a (patch) | |
tree | 5e57661720fe9058d5c7db637e764800b50f9060 /files/vi/web/javascript/reference/global_objects/array/reduce/index.html | |
parent | ee3b1c87e3c8e72ca130943eed260ad642246581 (diff) | |
download | translated-content-95aca4b4d8fa62815d4bd412fff1a364f842814a.tar.gz translated-content-95aca4b4d8fa62815d4bd412fff1a364f842814a.tar.bz2 translated-content-95aca4b4d8fa62815d4bd412fff1a364f842814a.zip |
remove retired locales (#699)
Diffstat (limited to 'files/vi/web/javascript/reference/global_objects/array/reduce/index.html')
-rw-r--r-- | files/vi/web/javascript/reference/global_objects/array/reduce/index.html | 553 |
1 files changed, 0 insertions, 553 deletions
diff --git a/files/vi/web/javascript/reference/global_objects/array/reduce/index.html b/files/vi/web/javascript/reference/global_objects/array/reduce/index.html deleted file mode 100644 index c665d37ad3..0000000000 --- a/files/vi/web/javascript/reference/global_objects/array/reduce/index.html +++ /dev/null @@ -1,553 +0,0 @@ ---- -title: Array.prototype.reduce() -slug: Web/JavaScript/Reference/Global_Objects/Array/Reduce -translation_of: Web/JavaScript/Reference/Global_Objects/Array/Reduce ---- -<div>{{JSRef}}</div> - -<p>Phương thức <code><strong>reduce()</strong></code> dùng để thực thi một hàm lên từng phần tử của mảng (từ trái sang phải) với một biến tích lũy để thu về một giá trị duy nhất.</p> - -<div>{{EmbedInteractiveExample("pages/js/array-reduce.html")}}</div> - - - -<h2 id="Cú_pháp">Cú pháp</h2> - -<pre class="syntaxbox"><var>arr</var>.reduce(<var>callback[, </var><var>initialValue]</var>)</pre> - -<h3 id="Các_tham_số">Các tham số</h3> - -<dl> - <dt><code>callback</code></dt> - <dd>Hàm dùng để thực thi với từng phần tử (element) của mảng, nhận vào 04 tham số: - <dl> - <dt><code>accumulator</code></dt> - <dd>Biến tích lũy, truyền giá trị trả về của mỗi lần gọi callback; nó là giá trị tích lũy được trả về trong lần gọi callback trước, hoặc giá trị của tham số <code>initialValue</code>, nếu được cung cấp (xem bên dưới).</dd> - <dt><code>currentValue</code></dt> - <dd>Phần tử trong mảng hiện tại đang được xử lý.</dd> - <dt><code>currentIndex</code>{{optional_inline}}</dt> - <dd>Chỉ mục (index) của phần tử đang được xử lý. Bắt đầu tại 0, nếu giá trị <code>initialValue</code> được cung cấp, và tại 1 nếu không có <code>initialValue</code>.</dd> - <dt><code>array</code>{{optional_inline}}</dt> - <dd>Mảng đang được gọi với <code>reduce()</code>.</dd> - </dl> - </dd> - <dt><code>initialValue</code>{{optional_inline}}</dt> - <dd>Giá trị cho tham số thứ nhất (<code>accumulator</code>) của hàm <code>callback</code> trong lần gọi đầu tiên. Nếu giá trị ban đầu này không được cung cấp, phần tử đầu tiên của mảng sẽ được dùng. Do đó, gọi <code>reduce()</code> trên một mảng rỗng và không có giá trị ban đầu sẽ gây ra lỗi.</dd> -</dl> - -<h3 id="Giá_trị_trả_về">Giá trị trả về</h3> - -<p>Giá trị sau khi rút gọn.</p> - -<h2 id="Mô_tả">Mô tả</h2> - -<p><code>reduce()</code> thực thi hàm <code>callback</code> lên từng phần tử đang tồn tại trong mảng, bỏ qua những lỗ trống không giá trị, và nhận vào 04 tham số:</p> - -<ul> - <li><code>accumulator</code></li> - <li><code>currentValue</code></li> - <li><code>currentIndex</code></li> - <li><code>array</code></li> -</ul> - -<p>Trong lần đầu tiên <code>callback</code> được gọi, <code>accumulator</code> and <code>currentValue</code> có thể có một trong hai giá trị. Nếu tham số <code>initialValue</code> được cung cấp cho <code>reduce()</code>, thì <code>accumulator</code> sẽ bằng <code>initialValue</code>, và <code>currentValue</code> sẽ bằng phần tử đầu tiên của mảng. Nếu không có <code>initialValue</code>, <code>accumulator</code> sẽ bằng phần tử đầu tiên của mảng, và <code>currentValue</code> sẽ bằng phần tử thứ hai.</p> - -<div class="note"> -<p><strong>Ghi chú:</strong> Nếu <code>initialValue</code> không được cung cấp, <code>reduce()</code> sẽ thực thi callback bắt đầu từ index 1, bỏ qua index đầu tiên. Nếu <code>initialValue</code> được cung cấp, index sẽ bắt đầu từ 0.</p> -</div> - -<p>Nếu mảng rỗng, và <code>initialValue</code> không được cung cấp, gọi <code>reduce()</code> sẽ gây ra lỗi {{jsxref("TypeError")}}. Nếu mảng chỉ có một phần tử có giá trị (bất kể vị trí index) đồng thời không có <code>initialValue</code>, hoặc có <code>initialValue</code> nhưng mảng lại rỗng, thì giá trị duy nhất đó sẽ được trả về và <em><code>callback</code> sẽ không được gọi</em>.</p> - -<p>Sẽ an toàn hơn nếu giá trị ban đầu được cung cấp, bởi vì có đến ba khả năng xảy ra nếu không có <code>initialValue</code> như ở ví dụ sau:</p> - -<pre class="brush: js">var maxCallback = ( acc, cur ) => Math.max( acc.x, cur.x ); -var maxCallback2 = ( max, cur ) => Math.max( max, cur ); - -// reduce() không có initialValue -[ { x: 22 }, { x: 42 } ].reduce( maxCallback ); // 42 -[ { x: 22 } ].reduce( maxCallback ); // { x: 22 } -[ ].reduce( maxCallback ); // TypeError - -// map/reduce; giải pháp hay hơn, và nó có thể áp dụng được cho mảng rỗng hoặc lớn hơn -[ { x: 22 }, { x: 42 } ].map( el => el.x ) - .reduce( maxCallback2, -Infinity ); -</pre> - -<h3 id="Cách_reduce()_làm_việc">Cách reduce() làm việc</h3> - -<p>Giả sử có một đoạn code với <code>reduce()</code> được hiện thực như sau:</p> - -<pre class="brush: js">[0, 1, 2, 3, 4].reduce(function(accumulator, currentValue, currentIndex, array) { - return accumulator + currentValue; -}); -</pre> - -<p>Callback sẽ được gọi bốn lần, với giá trị tham số và trả về trong mỗi lần gọi như sau:</p> - -<table> - <thead> - <tr> - <th scope="col"><code>callback</code></th> - <th scope="col"><code>accumulator</code></th> - <th scope="col"><code>currentValue</code></th> - <th scope="col"><code>currentIndex</code></th> - <th scope="col"><code>array</code></th> - <th scope="col">giá trị trả về</th> - </tr> - </thead> - <tbody> - <tr> - <th scope="row">lần gọi thứ nhất</th> - <td><code>0</code></td> - <td><code>1</code></td> - <td>1</td> - <td><code>[0, 1, 2, 3, 4]</code></td> - <td><code>1</code></td> - </tr> - <tr> - <th scope="row">lần gọi thứ hai</th> - <td><code>1</code></td> - <td><code>2</code></td> - <td>2</td> - <td><code>[0, 1, 2, 3, 4]</code></td> - <td><code>3</code></td> - </tr> - <tr> - <th scope="row">lần gọi thứ ba</th> - <td><code>3</code></td> - <td><code>3</code></td> - <td>3</td> - <td><code>[0, 1, 2, 3, 4]</code></td> - <td><code>6</code></td> - </tr> - <tr> - <th scope="row">lần gọi thứ tư</th> - <td><code>6</code></td> - <td><code>4</code></td> - <td>4</td> - <td><code>[0, 1, 2, 3, 4]</code></td> - <td><code>10</code></td> - </tr> - </tbody> -</table> - -<p>Giá trị trả về cho <code>reduce()</code> chính là giá trị trả về của lần gọi callback cuối cùng (<code>10</code>).</p> - -<p>Bạn cũng có thể cung cấp một hàm mũi tên {{jsxref("Functions/Arrow_functions", "Arrow Function","",1)}} thay vì một hàm đầy đủ. Đoạn code sau đây sẽ cho kết quả giống như đoạn code ở trên:</p> - -<pre class="brush: js">[0, 1, 2, 3, 4].reduce( (accumulator, currentValue, currentIndex, array) => accumulator + currentValue ); -</pre> - -<p>Nếu bạn cung cấp giá trị <code>initialValue</code> cho tham số thứ hai của hàm <code>reduce()</code>, thì kết quả sẽ như bên dưới:</p> - -<pre class="brush: js">[0, 1, 2, 3, 4].reduce((accumulator, currentValue, currentIndex, array) => { - return accumulator + currentValue; -}, 10); -</pre> - -<table> - <thead> - <tr> - <th scope="col"><code>callback</code></th> - <th scope="col"><code>accumulator</code></th> - <th scope="col"><code>currentValue</code></th> - <th scope="col"><code>currentIndex</code></th> - <th scope="col"><code>array</code></th> - <th scope="col">giá trị trả về</th> - </tr> - </thead> - <tbody> - <tr> - <th scope="row">lần gọi thứ nhất</th> - <td><code>10</code></td> - <td><code>0</code></td> - <td><code>0</code></td> - <td><code>[0, 1, 2, 3, 4]</code></td> - <td><code>10</code></td> - </tr> - <tr> - <th scope="row">lần gọi thứ hai</th> - <td><code>10</code></td> - <td><code>1</code></td> - <td><code>1</code></td> - <td><code>[0, 1, 2, 3, 4]</code></td> - <td><code>11</code></td> - </tr> - <tr> - <th scope="row">lần gọi thứ ba</th> - <td><code>11</code></td> - <td><code>2</code></td> - <td><code>2</code></td> - <td><code>[0, 1, 2, 3, 4]</code></td> - <td><code>13</code></td> - </tr> - <tr> - <th scope="row">lần gọi thứ tư</th> - <td><code>13</code></td> - <td><code>3</code></td> - <td><code>3</code></td> - <td><code>[0, 1, 2, 3, 4]</code></td> - <td><code>16</code></td> - </tr> - <tr> - <th scope="row">lần gọi thứ năm</th> - <td><code>16</code></td> - <td><code>4</code></td> - <td><code>4</code></td> - <td><code>[0, 1, 2, 3, 4]</code></td> - <td><code>20</code></td> - </tr> - </tbody> -</table> - -<p>Giá trị trả về cho <code>reduce()</code> lần này sẽ là <code>20</code>.</p> - -<h2 id="Ví_dụ">Ví dụ</h2> - -<h3 id="Tính_tổng_của_tất_cả_các_phần_tử_của_mảng">Tính tổng của tất cả các phần tử của mảng</h3> - -<pre class="brush: js">var sum = [0, 1, 2, 3].reduce(function (accumulator, currentValue) { - return accumulator + currentValue; -}, 0); -// sum is 6 - -</pre> - -<p>Tương tự, nhưng viết bằng hàm arrow function</p> - -<pre class="brush: js">var total = [ 0, 1, 2, 3 ].reduce( - ( accumulator, currentValue ) => accumulator + currentValue, - 0 -);</pre> - -<h3 id="Tính_tổng_các_giá_trị_bên_trong_một_mảng_các_object">Tính tổng các giá trị bên trong một mảng các object</h3> - -<p>Để tính tổng các giá trị nằm bên trong các phần tử là object, bạn <strong>phải</strong> cung cấp một giá trị ban đầu để từng phần tử đều được callback chạy qua (và <code>accumulator</code> luôn luôn là giá trị kiểu số):</p> - -<pre class="brush: js">var initialValue = 0; -var sum = [{x: 1}, {x:2}, {x:3}].reduce(function (accumulator, currentValue) { - return accumulator + currentValue.x; -},initialValue) - -console.log(sum) // logs 6 -</pre> - -<p>Tương tự, viết bằng arrow function:</p> - -<pre class="brush: js">var initialValue = 0; -var sum = [{x: 1}, {x:2}, {x:3}].reduce( - (accumulator, currentValue) => accumulator + currentValue.x - ,initialValue -); - -console.log(sum) // logs 6</pre> - -<h3 id="Trải_phẳng_một_mảng_chứa_nhiều_mảng_con">Trải phẳng một mảng chứa nhiều mảng con</h3> - -<pre class="brush: js">var flattened = [[0, 1], [2, 3], [4, 5]].reduce( - function(accumulator, currentValue) { - return accumulator.concat(currentValue); - }, - [] -); -// flattened is [0, 1, 2, 3, 4, 5] -</pre> - -<p>Tương tự, viết bằng arrow function:</p> - -<pre class="brush: js">var flattened = [[0, 1], [2, 3], [4, 5]].reduce( - ( accumulator, currentValue ) => accumulator.concat(currentValue), - [] -); -</pre> - -<h3 id="Đếm_số_lần_xuất_hiện_của_phần_tử_trong_mảng">Đếm số lần xuất hiện của phần tử trong mảng</h3> - -<pre class="brush: js">var names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice']; - -var countedNames = names.reduce(function (allNames, name) { - if (name in allNames) { - allNames[name]++; - } - else { - allNames[name] = 1; - } - return allNames; -}, {}); -// countedNames is: -// { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 } -</pre> - -<h3 id="Nhóm_các_đối_tượng_theo_giá_trị_property_nào_đó">Nhóm các đối tượng theo giá trị property nào đó</h3> - -<pre class="brush: js">var people = [ - { name: 'Alice', age: 21 }, - { name: 'Max', age: 20 }, - { name: 'Jane', age: 20 } -]; - -function groupBy(objectArray, property) { - return objectArray.reduce(function (acc, obj) { - var key = obj[property]; - if (!acc[key]) { - acc[key] = []; - } - acc[key].push(obj); - return acc; - }, {}); -} - -var groupedPeople = groupBy(people, 'age'); -// groupedPeople is: -// { -// 20: [ -// { name: 'Max', age: 20 }, -// { name: 'Jane', age: 20 } -// ], -// 21: [{ name: 'Alice', age: 21 }] -// } -</pre> - -<h3 id="Ghép_các_mảng_con_bên_trong_các_object_sử_dụng_toán_tử_spread_và_initialValue">Ghép các mảng con bên trong các object sử dụng toán tử spread và initialValue</h3> - -<pre class="brush: js">// friends - an array of objects -// where object field "books" - list of favorite books -var friends = [{ - name: 'Anna', - books: ['Bible', 'Harry Potter'], - age: 21 -}, { - name: 'Bob', - books: ['War and peace', 'Romeo and Juliet'], - age: 26 -}, { - name: 'Alice', - books: ['The Lord of the Rings', 'The Shining'], - age: 18 -}]; - -// allbooks - list which will contain all friends' books + -// additional list contained in initialValue -var allbooks = friends.reduce(function(accumulator, currentValue) { - return [...accumulator, ...currentValue.books]; -}, ['Alphabet']); - -// allbooks = [ -// 'Alphabet', 'Bible', 'Harry Potter', 'War and peace', -// 'Romeo and Juliet', 'The Lord of the Rings', -// 'The Shining' -// ]</pre> - -<h3 id="Xóa_các_phần_tử_bị_trùng_trong_mảng">Xóa các phần tử bị trùng trong mảng</h3> - -<pre class="brush: js">let arr = [1, 2, 1, 2, 3, 5, 4, 5, 3, 4, 4, 4, 4]; -let result = arr.sort().reduce((accumulator, current) => { - const length = accumulator.length - if (length === 0 || accumulator[length - 1] !== current) { - accumulator.push(current); - } - return accumulator; -}, []); -console.log(result); //[1,2,3,4,5] -</pre> - -<h3 id="Chạy_các_Promise_theo_trình_tự">Chạy các Promise theo trình tự</h3> - -<pre class="brush: js">/** - * Runs promises from array of functions that can return promises - * in chained manner - * - * @param {array} arr - promise arr - * @return {Object} promise object - */ -function runPromiseInSequence(arr, input) { - return arr.reduce( - (promiseChain, currentFunction) => promiseChain.then(currentFunction), - Promise.resolve(input) - ); -} - -// promise function 1 -function p1(a) { - return new Promise((resolve, reject) => { - resolve(a * 5); - }); -} - -// promise function 2 -function p2(a) { - return new Promise((resolve, reject) => { - resolve(a * 2); - }); -} - -// function 3 - will be wrapped in a resolved promise by .then() -function f3(a) { - return a * 3; -} - -// promise function 4 -function p4(a) { - return new Promise((resolve, reject) => { - resolve(a * 4); - }); -} - -const promiseArr = [p1, p2, f3, p4]; -runPromiseInSequence(promiseArr, 10) - .then(console.log); // 1200 -</pre> - -<h3 id="Tổ_hợp_các_hàm_và_gọi_chuyền_(piping)">Tổ hợp các hàm và gọi chuyền (piping)</h3> - -<pre class="brush: js">// Building-blocks to use for composition -const double = x => x + x; -const triple = x => 3 * x; -const quadruple = x => 4 * x; - -// Function composition enabling pipe functionality -const pipe = (...functions) => input => functions.reduce( - (acc, fn) => fn(acc), - input -); - -// Composed functions for multiplication of specific values -const multiply6 = pipe(double, triple); -const multiply9 = pipe(triple, triple); -const multiply16 = pipe(quadruple, quadruple); -const multiply24 = pipe(double, triple, quadruple); - -// Usage -multiply6(6); // 36 -multiply9(9); // 81 -multiply16(16); // 256 -multiply24(10); // 240 - -</pre> - -<h3 id="Hiện_thực_lại_map()_sử_dụng_reduce()">Hiện thực lại map() sử dụng reduce()</h3> - -<pre class="brush: js">if (!Array.prototype.mapUsingReduce) { - Array.prototype.mapUsingReduce = function(callback, thisArg) { - return this.reduce(function(mappedArray, currentValue, index, array) { - mappedArray[index] = callback.call(thisArg, currentValue, index, array); - return mappedArray; - }, []); - }; -} - -[1, 2, , 3].mapUsingReduce( - (currentValue, index, array) => currentValue + index + array.length -); // [5, 7, , 10] - -</pre> - -<h2 id="Polyfill">Polyfill</h2> - -<pre class="brush: js">// Production steps of ECMA-262, Edition 5, 15.4.4.21 -// Reference: http://es5.github.io/#x15.4.4.21 -// https://tc39.github.io/ecma262/#sec-array.prototype.reduce -if (!Array.prototype.reduce) { - Object.defineProperty(Array.prototype, 'reduce', { - value: function(callback /*, initialValue*/) { - if (this === null) { - throw new TypeError( 'Array.prototype.reduce ' + - 'called on null or undefined' ); - } - if (typeof callback !== 'function') { - throw new TypeError( callback + - ' is not a function'); - } - - // 1. Let O be ? ToObject(this value). - var o = Object(this); - - // 2. Let len be ? ToLength(? Get(O, "length")). - var len = o.length >>> 0; - - // Steps 3, 4, 5, 6, 7 - var k = 0; - var value; - - if (arguments.length >= 2) { - value = arguments[1]; - } else { - while (k < len && !(k in o)) { - k++; - } - - // 3. If len is 0 and initialValue is not present, - // throw a TypeError exception. - if (k >= len) { - throw new TypeError( 'Reduce of empty array ' + - 'with no initial value' ); - } - value = o[k++]; - } - - // 8. Repeat, while k < len - while (k < len) { - // a. Let Pk be ! ToString(k). - // b. Let kPresent be ? HasProperty(O, Pk). - // c. If kPresent is true, then - // i. Let kValue be ? Get(O, Pk). - // ii. Let accumulator be ? Call( - // callbackfn, undefined, - // « accumulator, kValue, k, O »). - if (k in o) { - value = callback(value, o[k], k, o); - } - - // d. Increase k by 1. - k++; - } - - // 9. Return accumulator. - return value; - } - }); -} -</pre> - -<p>Nếu bạn thực sự cần chức năng này trên những engine JavaScript không hỗ trợ <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty">Object.defineProperty()</a></code>, bạn không nên thêm polyfill này vào <code>Array.prototype</code> bởi vì không có cách nào làm cho nó <em>không-duyệt-qua</em> (non-enumerable) được (property mới sẽ xuất hiện trong các vòng lặp for).</p> - -<h2 id="Đặc_tả">Đặc tả</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Đặc tả</th> - <th scope="col">Trạng thái</th> - <th scope="col">Ghi chú</th> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.4.4.21', 'Array.prototype.reduce()')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td>Định nghĩa lần đầu. Hiện thực trong JavaScript 1.8.</td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-array.prototype.reduce', 'Array.prototype.reduce()')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-array.prototype.reduce', 'Array.prototype.reduce()')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Tương_thích_trình_duyệt">Tương thích trình duyệt</h2> - -<div> - - -<p>{{Compat("javascript.builtins.Array.reduce")}}</p> -</div> - -<h2 id="Xem_thêm">Xem thêm</h2> - -<ul> - <li>{{jsxref("Array.prototype.reduceRight()")}}</li> -</ul> |