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/uk/web/javascript/reference/global_objects/array/reduceright | |
| 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/uk/web/javascript/reference/global_objects/array/reduceright')
| -rw-r--r-- | files/uk/web/javascript/reference/global_objects/array/reduceright/index.html | 364 |
1 files changed, 0 insertions, 364 deletions
diff --git a/files/uk/web/javascript/reference/global_objects/array/reduceright/index.html b/files/uk/web/javascript/reference/global_objects/array/reduceright/index.html deleted file mode 100644 index 2471147574..0000000000 --- a/files/uk/web/javascript/reference/global_objects/array/reduceright/index.html +++ /dev/null @@ -1,364 +0,0 @@ ---- -title: Array.prototype.reduceRight() -slug: Web/JavaScript/Reference/Global_Objects/Array/ReduceRight -tags: - - Array - - ECMAScript5 - - JavaScript - - Масив - - метод -translation_of: Web/JavaScript/Reference/Global_Objects/Array/ReduceRight ---- -<div>{{JSRef}}</div> - -<p>Метод <code><strong>reduceRight()</strong></code> застосовує функцію до акумулятора та кожного елемента масиву (справа наліво), зменшуючи його до єдиного значення.</p> - -<div>{{EmbedInteractiveExample("pages/js/array-reduce-right.html")}}</div> - - - -<p>Дивіться також {{jsxref("Array.prototype.reduce()")}}, який виконується зліва направо.</p> - -<h2 id="Синтаксис">Синтаксис</h2> - -<pre class="syntaxbox"><var>arr.reduceRight(callback(accumulator, currentValue[, index[, array]])[, initialValue])</var></pre> - -<h3 id="Параметри">Параметри</h3> - -<dl> - <dt><code>callback</code></dt> - <dd>Функція, яка виконується на кожному елементі масиву. Приймає чотири аргументи: - <dl> - <dt><code>accumulator</code></dt> - <dd>Значення, яке було повернене з попереднього виклику функції, або <code>initialValue</code>, якщо є. (Дивіться нижче.)</dd> - <dt><code>currentValue</code></dt> - <dd>Поточний елемент масиву, що опрацьовується.</dd> - <dt><code>index</code>{{optional_inline}}</dt> - <dd>Індекс поточного елемента масиву.</dd> - <dt><code>array</code>{{optional_inline}}</dt> - <dd>Масив, для якого було викликано <code>reduceRight()</code>.</dd> - </dl> - </dd> - <dt><code>initialValue</code>{{optional_inline}}</dt> - <dd>Значення, що використовується в якості акумулятора для першого виклику <code>callback</code>. Якщо початкового значення нема, то буде використаний та пропущений останній елемент масиву. Виклик <code>reduce</code> або <code>reduceRight</code> на порожньому масиві без початкового значення створить виняток <code>TypeError</code>.</dd> -</dl> - -<h3 id="Значення_яке_повертається">Значення, яке повертається</h3> - -<p>Значення, що є результатом зменшення.</p> - -<h2 id="Опис">Опис</h2> - -<p>Метод <code>reduceRight</code> виконує функцію зворотного виклику один раз для кожного елемента у масиві, крім порожніх елементів, отримуючи чотири аргументи: початкове значення (або значення від попереднього виклику функції), значення поточного елемента, поточний індекс та масив, обхід якого виконується.</p> - -<p>Виклик функції <code>callback</code> у reduceRight виглядатиме десь так:</p> - -<pre class="brush: js">array.reduceRight(function(accumulator, currentValue, index, array) { - // ... -}); -</pre> - -<p>Коли функція викликається вперше, <code>accumulator</code> та <code>currentValue</code> можуть мати одне з двох значень. Якщо значення <code>initialValue</code> було надане під час виклику <code>reduceRight</code>, тоді <code>accumulator</code> дорівнюватиме <code>initialValue</code>, а <code>currentValue</code> останньому елементу масиву. Якщо значення <code>initialValue</code> не визначено, тоді <code>accumulator</code> дорівнюватиме останньому елементу масиву, а <code>currentValue</code> передостанньому.</p> - -<p>Якщо масив порожній, а <code>initialValue</code> не надано, то буде викинуто виняток {{jsxref("TypeError")}}. Якщо масив має лише один елемент (незалежно від позиції), і немає значення <code>initialValue</code>, або якщо <code>initialValue</code> надано, але масив порожній, це єдине значення повернеться без виклику <code>callback</code>.</p> - -<p>Для прикладу, функція може виглядати так:</p> - -<pre class="brush: js">[0, 1, 2, 3, 4].reduceRight(function(accumulator, currentValue, index, array) { - return accumulator + currentValue; -}); -</pre> - -<p>Функція зворотного виклику буде виконана чотири рази, аргументи та значення, які повертаються, наведені нижче:</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>index</code></th> - <th scope="col"><code>array</code></th> - <th scope="col">вертає</th> - </tr> - </thead> - <tbody> - <tr> - <th scope="row">перший виклик</th> - <td><code>4</code></td> - <td><code>3</code></td> - <td><code>3</code></td> - <td><code>[0, 1, 2, 3, 4]</code></td> - <td><code>7</code></td> - </tr> - <tr> - <th scope="row">другий виклик</th> - <td><code>7</code></td> - <td><code>2</code></td> - <td><code>2</code></td> - <td><code>[0, 1, 2, 3, 4]</code></td> - <td><code>9</code></td> - </tr> - <tr> - <th scope="row">третій виклик</th> - <td><code>9</code></td> - <td><code>1</code></td> - <td><code>1</code></td> - <td><code>[0, 1, 2, 3, 4]</code></td> - <td><code>10</code></td> - </tr> - <tr> - <th scope="row">четвертий виклик</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> - </tbody> -</table> - -<p>Значення, яке повертає <code>reduceRight</code> буде тим, яке вертає останній виклик <code>callback</code> (<code>10</code>).</p> - -<p>А якби ви надали значення <code>initialValue</code>, результат виглядав би так:</p> - -<pre class="brush: js">[0, 1, 2, 3, 4].reduceRight(function(accumulator, currentValue, index, 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>index</code></th> - <th scope="col"><code>array</code></th> - <th scope="col">вертає</th> - </tr> - </thead> - <tbody> - <tr> - <th scope="row">перший виклик</th> - <td><code>10</code></td> - <td><code>4</code></td> - <td><code>4</code></td> - <td><code>[0, 1, 2, 3, 4]</code></td> - <td><code>14</code></td> - </tr> - <tr> - <th scope="row">другий виклик</th> - <td><code>14</code></td> - <td><code>3</code></td> - <td><code>3</code></td> - <td><code>[0, 1, 2, 3, 4]</code></td> - <td><code>17</code></td> - </tr> - <tr> - <th scope="row">третій виклик</th> - <td><code>17</code></td> - <td><code>2</code></td> - <td><code>2</code></td> - <td><code>[0, 1, 2, 3, 4]</code></td> - <td><code>19</code></td> - </tr> - <tr> - <th scope="row">четвертий виклик</th> - <td><code>19</code></td> - <td><code>1</code></td> - <td><code>1</code></td> - <td><code>[0, 1, 2, 3, 4]</code></td> - <td><code>20</code></td> - </tr> - <tr> - <th scope="row">п'ятий виклик</th> - <td><code>20</code></td> - <td><code>0</code></td> - <td><code>0</code></td> - <td><code>[0, 1, 2, 3, 4]</code></td> - <td><code>20</code></td> - </tr> - </tbody> -</table> - -<p>Цього разу <code>reduceRight</code>, звісно, повернув би <code>20</code>.</p> - -<h2 id="Приклади">Приклади</h2> - -<h3 id="Знайти_суму_елементів_масиву">Знайти суму елементів масиву</h3> - -<pre class="brush: js">var sum = [0, 1, 2, 3].reduceRight(function(a, b) { - return a + b; -}); -// сума дорівнює 6 -</pre> - -<h3 id="Вирівняти_масив_масивів">Вирівняти масив масивів</h3> - -<pre class="brush: js">var flattened = [[0, 1], [2, 3], [4, 5]].reduceRight(function(a, b) { - return a.concat(b); -}, []); -// Результат [4, 5, 2, 3, 0, 1] - -</pre> - -<h3 id="Виконати_послідовно_набір_асинхронних_функцій_з_функціями_зворотного_виклику_щоб_кожна_передавала_свій_результат_у_наступну">Виконати послідовно набір асинхронних функцій з функціями зворотного виклику, щоб кожна передавала свій результат у наступну</h3> - -<pre class="brush: js">const waterfall = (...functions) => (callback, ...args) => - functions.reduceRight( - (composition, fn) => (...results) => fn(composition, ...results), - callback - )(...args); - -const randInt = max => Math.floor(Math.random() * max) - -const add5 = (callback, x) => { - setTimeout(callback, randInt(1000), x + 5); -}; -const mult3 = (callback, x) => { - setTimeout(callback, randInt(1000), x * 3); -}; -const sub2 = (callback, x) => { - setTimeout(callback, randInt(1000), x - 2); -}; -const split = (callback, x) => { - setTimeout(callback, randInt(1000), x, x); -}; -const add = (callback, x, y) => { - setTimeout(callback, randInt(1000), x + y); -}; -const div4 = (callback, x) => { - setTimeout(callback, randInt(1000), x / 4); -}; - -const computation = waterfall(add5, mult3, sub2, split, add, div4); -computation(console.log, 5) // -> 14 - -// те саме, що й: - -const computation2 = (input, callback) => { - const f6 = x=> div4(callback, x); - const f5 = (x, y) => add(f6, x, y); - const f4 = x => split(f5, x); - const f3 = x => sub2(f4, x); - const f2 = x => mult3(f3, x); - add5(f2, input); -}</pre> - -<h3 id="Різниця_між_reduce_та_reduceRight">Різниця між <code>reduce</code> та <code>reduceRight</code></h3> - -<pre class="brush: js">var a = ['1', '2', '3', '4', '5']; -var left = a.reduce(function(prev, cur) { return prev + cur; }); -var right = a.reduceRight(function(prev, cur) { return prev + cur; }); - -console.log(left); // "12345" -console.log(right); // "54321"</pre> - -<h3 id="Визначення_композиції_функцій">Визначення композиції функцій</h3> - -<p>Концепція композиції функцій проста - вона об'єднує функції. Це послідовний, справа наліво, виклик кожної функції з результатом попередньої.</p> - -<pre class="brush: js">/** - * Композиція функцій - це підхід, в якому результат однієї функції - * передається у іншу і т.д. - * - * h(x) = f(g(x)) - * - * Виконання функцій відбувається справа наліво - * - * <a href="https://uk.wikipedia.org/wiki/Композиція_функцій">https://uk.wikipedia.org/wiki/Композиція_функцій</a> - */ - -const compose = (...args) => (value) => args.reduceRight((acc, fn) => fn(acc), value) - -// Збільшує передане число на 1 -const inc = (n) => n + 1 - -// Подвоює передане значення -const double = (n) => n * 2 - -// використання композиції функцій -console.log(compose(double, inc)(2)); // 6 - -// використання композиції функцій -console.log(compose(inc, double)(2)); // 5 -</pre> - -<h2 id="Поліфіл">Поліфіл</h2> - -<p>Метод <code>reduceRight</code> був доданий до стандарту ECMA-262 у 5-й версії; таким чином, він може не бути присутній у всіх реалізаціях стандарту. Ви можете обійти цю проблему, вставивши наступний код на початку ваших скриптів, це дозволить використовувати метод <code>reduceRight</code> у версіях, які не підтримують його початково.</p> - -<pre class="brush: js">// Функціональні кроки ECMA-262, версія 5, 15.4.4.22 -// Довідка: http://es5.github.io/#x15.4.4.22 -if ('function' !== typeof Array.prototype.reduceRight) { - Array.prototype.reduceRight = function(callback /*, initialValue*/) { - 'use strict'; - if (null === this || 'undefined' === typeof this) { - throw new TypeError('Array.prototype.reduce called on null or undefined'); - } - if ('function' !== typeof callback) { - throw new TypeError(callback + ' is not a function'); - } - var t = Object(this), len = t.length >>> 0, k = len - 1, value; - if (arguments.length >= 2) { - value = arguments[1]; - } else { - while (k >= 0 && !(k in t)) { - k--; - } - if (k < 0) { - throw new TypeError('Reduce of empty array with no initial value'); - } - value = t[k--]; - } - for (; k >= 0; k--) { - if (k in t) { - value = callback(value, t[k], k, t); - } - } - return value; - }; -} -</pre> - -<h2 id="Специфікації">Специфікації</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Специфікація</th> - <th scope="col">Статус</th> - <th scope="col">Коментар</th> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.4.4.22', 'Array.prototype.reduceRight')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td>Початкове визначення. Реалізоване у JavaScript 1.8.</td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-array.prototype.reduceright', 'Array.prototype.reduceRight')}}</td> - <td>{{Spec2('ES6')}}</td> - <td></td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-array.prototype.reduceright', 'Array.prototype.reduceRight')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td></td> - </tr> - </tbody> -</table> - -<h2 id="Сумісність_з_веб-переглядачами">Сумісність з веб-переглядачами</h2> - -<div> - - -<p>{{Compat("javascript.builtins.Array.reduceRight")}}</p> -</div> - -<h2 id="Див._також">Див. також</h2> - -<ul> - <li>{{jsxref("Array.prototype.reduce()")}}</li> -</ul> |
