diff options
Diffstat (limited to 'files/ja/web/javascript/reference/global_objects/array')
4 files changed, 489 insertions, 486 deletions
diff --git a/files/ja/web/javascript/reference/global_objects/array/includes/index.html b/files/ja/web/javascript/reference/global_objects/array/includes/index.html deleted file mode 100644 index b78bb5d20e..0000000000 --- a/files/ja/web/javascript/reference/global_objects/array/includes/index.html +++ /dev/null @@ -1,135 +0,0 @@ ---- -title: Array.prototype.includes() -slug: Web/JavaScript/Reference/Global_Objects/Array/includes -tags: - - Array - - JavaScript - - Method - - Prototype - - Reference - - inArray - - in_array - - polyfill - - メソッド -translation_of: Web/JavaScript/Reference/Global_Objects/Array/includes ---- -<div>{{JSRef}}</div> - -<p><code><strong>includes()</strong></code> メソッドは、特定の要素が配列に含まれているかどうかを <code>true</code> または <code>false</code> で返します。</p> - -<div>{{EmbedInteractiveExample("pages/js/array-includes.html")}}</div> - -<div class="hidden">このデモのソースファイルは GitHub リポジトリに格納されています。デモプロジェクトに協力したい場合は、<a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> をクローンしてプルリクエストを送信してください。</div> - -<h2 id="Syntax" name="Syntax">構文</h2> - -<pre class="syntaxbox notranslate"><var>arr</var>.includes(<var>valueToFind</var>[, <var>fromIndex</var>]) -</pre> - -<h3 id="Parameters" name="Parameters">引数</h3> - -<dl> - <dt><code><var>valueToFind</var></code></dt> - <dd> - <p>検索する値です。</p> - - <div class="blockIndicator note"> - <p><strong>メモ:</strong> 文字列や文字を比較するとき、<code>includes()</code> は<em>大文字と小文字を区別します</em>。</p> - </div> - </dd> - <dt><code><var>fromIndex</var></code> {{optional_inline}}</dt> - <dd>この配列内で <code><var>valueToFind</var></code> を探し始める位置です。</dd> - <dd>検索される最初の文字は、<code><var>fromIndex</var></code> が正の値の場合は、<code><var>fromIndex</var></code> で見つかり、<code><var>fromIndex</var></code> が負の数の場合は (<code><var>fromIndex</var></code> の{{interwiki("wikipedia", "絶対値")}}だけ配列の末尾から文字数を戻った位置が検索開始地点となり)、<code><var>fromIndex</var></code> または <code><var>arr</var>.length + fromIndex</code> で見つかります。</dd> - <dd>既定値は 0 です。</dd> -</dl> - -<h3 id="Return_value" name="Return_value">返値</h3> - -<p>{{jsxref("Boolean")}} で、<code>true</code> は <code><var>valueToFind</var></code> の値が配列内 (または、<code><var>fromIndex</var></code> が指定された場合はそれで示された配列の部分) から見つかった場合です。</p> - -<p>ゼロの値はすべて、符号にかかわらず等しいとみなされます (つまり、<code>-0</code> は <code>0</code> と <code>+0</code> の両方に等しいとみなされます) が、<code>false</code> は <code>0</code> と同じとはみなされ<em>ません</em>。</p> - -<div class="note"> -<p><strong>注:</strong> 技術的に言えば、<code>includes()</code> は <code><a href="/ja/docs/Web/JavaScript/Equality_comparisons_and_sameness#Same-value-zero_equality">sameValueZero</a></code> アルゴリズムを使用して、指定された要素が見つかったかどうかを確認しています。</p> -</div> - -<h2 id="Examples" name="Examples">例</h2> - -<pre class="brush: js notranslate">[1, 2, 3].includes(2) // true -[1, 2, 3].includes(4) // false -[1, 2, 3].includes(3, 3) // false -[1, 2, 3].includes(3, -1) // true -[1, 2, NaN].includes(NaN) // true -</pre> - -<h3 id="fromIndex_is_greater_than_or_equal_to_the_array_length" name="fromIndex_is_greater_than_or_equal_to_the_array_length"><code><var>fromIndex</var></code> が配列の長さと同じか大きい場合</h3> - -<p><code><var>fromIndex</var></code> が配列の長さと同じか大きい場合は配列を検索せずに <code>false</code> を返します。</p> - -<pre class="brush: js notranslate">let arr = ['a', 'b', 'c'] - -arr.includes('c', 3) // false -arr.includes('c', 100) // false -</pre> - -<h3 id="Computed_index_is_less_than_0" name="Computed_index_is_less_than_0">計算値のインデックスが 0 より小さい場合</h3> - -<p><code><var>fromIndex</var></code> が負の値である場合、計算値のインデックスは配列内で <code><var>valueToFind</var></code> の円策を開始する位置として使用するよう計算されます。計算値のインデックスが <code>-1 * <var>arr</var>.length</code> 以下の場合は、配列全体が検索されます。</p> - -<pre class="brush: js notranslate">// 配列の長さは 3 -// fromIndex は -100 -// 補正されたインデックスは 3 + (-100) = -97 - -let arr = ['a', 'b', 'c'] - -arr.includes('a', -100) // true -arr.includes('b', -100) // true -arr.includes('c', -100) // true -arr.includes('a', -2) // false -</pre> - -<h3 id="includes_used_as_a_generic_method" name="includes_used_as_a_generic_method">ジェネリックメソッドとして使用される includes()</h3> - -<p><code>includes()</code> メソッドは意図的にジェネリックになっています。<code>this</code> が Array オブジェクトであることは必須ではないので、他の種類のオブジェクト (例えば配列風オブジェクト) にも適用することができます。</p> - -<p>以下の例は、<code>includes()</code> メソッドが関数の <a href="/ja/docs/Web/JavaScript/Reference/Functions/arguments">arguments</a> オブジェクトに対して使用される様子を示しています。</p> - -<pre class="brush: js notranslate">(function() { - console.log(Array.prototype.includes.call(arguments, 'a')) // true - console.log(Array.prototype.includes.call(arguments, 'd')) // false -})('a','b','c') </pre> - -<div class="hidden"> -<p>参照記事にポリフィルを追加しないでください。詳細や議論については、<a href="https://discourse.mozilla.org/t/mdn-rfc-001-mdn-wiki-pages-shouldnt-be-a-distributor-of-polyfills/24500">https://discourse.mozilla.org/t/mdn-rfc-001-mdn-wiki-pages-shouldnt-be-a-distributor-of-polyfills/24500</a> を参照して下さい。</p> -</div> - -<h2 id="Specifications" name="Specifications">仕様</h2> - -<table class="standard-table"> - <thead> - <tr> - <th scope="col">仕様書</th> - </tr> - </thead> - <tbody> - <tr> - <td>{{SpecName('ESDraft', '#sec-array.prototype.includes', 'Array.prototype.includes')}}</td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility" name="Browser_compatibility">ブラウザーの互換性</h2> - -<div> -<p>{{Compat("javascript.builtins.Array.includes")}}</p> -</div> - -<h2 id="See_also" name="See_also">関連情報</h2> - -<ul> - <li>{{jsxref("TypedArray.prototype.includes()")}}</li> - <li>{{jsxref("String.prototype.includes()")}}</li> - <li>{{jsxref("Array.prototype.indexOf()")}}</li> - <li>{{jsxref("Array.prototype.find()")}}</li> - <li>{{jsxref("Array.prototype.findIndex()")}}</li> -</ul> diff --git a/files/ja/web/javascript/reference/global_objects/array/includes/index.md b/files/ja/web/javascript/reference/global_objects/array/includes/index.md new file mode 100644 index 0000000000..e96597dcd1 --- /dev/null +++ b/files/ja/web/javascript/reference/global_objects/array/includes/index.md @@ -0,0 +1,120 @@ +--- +title: Array.prototype.includes() +slug: Web/JavaScript/Reference/Global_Objects/Array/includes +tags: + - Array + - JavaScript + - メソッド + - プロトタイプ + - リファレンス + - inArray + - in_array + - ポリフィル +browser-compat: javascript.builtins.Array.includes +translation_of: Web/JavaScript/Reference/Global_Objects/Array/includes +--- +{{JSRef}} + +**`includes()`** メソッドは、特定の要素が配列に含まれているかどうかを `true` または `false` で返します。 + +{{EmbedInteractiveExample("pages/js/array-includes.html")}} + +## 構文 + +```js +includes(searchElement) +includes(searchElement, fromIndex) +``` + +### 引数 + +- `searchElement` + + - : 検索する値です。 + + > **Note:** 文字列や文字を比較する場合、`includes()` は*大文字と小文字を区別します*。 + +- `fromIndex` {{optional_inline}} + + - : `searchElement` の検索を始める配列内の位置です。 + + 検索される最初の要素は、`fromIndex` が正の値の場合は `fromIndex` の位置に、`fromIndex` が負の値の場合は `arr.length + fromIndex` の位置になります (検索を開始する配列の端からの要素数として fromIndex の{{interwiki("wikipedia", "絶対値")}}を使用します)。 + + 既定値は `0` です。 + +### 返値 + +論理型で、`searchElement` の値が配列内 (`fromIndex` が指定されていた場合は、配列のその位置以降の部分) にあった場合は `true` を返します。 + +ゼロの値は符号に関わらず、すべて等しいとみなされます (すなわち、`-0` は `0` とも `+0` 友等しいとみなされます) が、`false` は `0` と同じとはみなされ*ません*。 + +> **Note:** 技術的に言えば、`includes()` は [`sameValueZero`](/ja/docs/Web/JavaScript/Equality_comparisons_and_sameness#same-value-zero_equality) アルゴリズムを使用して、指定された要素が見つかったかどうかを確認しています。 + +## 例 + +```js +[1, 2, 3].includes(2) // true +[1, 2, 3].includes(4) // false +[1, 2, 3].includes(3, 3) // false +[1, 2, 3].includes(3, -1) // true +[1, 2, NaN].includes(NaN) // true +["1", "2", "3"].includes(3) // false +``` + +### `fromIndex` が配列の長さと同じか大きい場合 + +`fromIndex` が配列の長さと同じか大きい場合は、配列を検索せずに `false` を返します。 + +```js +let arr = ['a', 'b', 'c'] + +arr.includes('c', 3) // false +arr.includes('c', 100) // false +``` + +### 計算された位置が 0 より小さい場合 + +`fromIndex` が負の値である場合、`searchElement` の検索を開始するための配列内の位置として、計算により位置が算出されます。計算された位置が `0` 以下の場合は、配列全体が検索されます。 + +```js +// 配列の長さは 3 +// fromIndex は -100 +// 補正されたインデックスは 3 + (-100) = -97 + +let arr = ['a', 'b', 'c'] + +arr.includes('a', -100) // true +arr.includes('b', -100) // true +arr.includes('c', -100) // true +arr.includes('a', -2) // false +``` + +### ジェネリックメソッドとして使用される includes() + +`includes()` メソッドは意図的にジェネリックになっています。`this` が Array オブジェクトであることは必須ではないので、他の種類のオブジェクト (例えば配列風オブジェクト) にも適用することができます。 + +以下の例は、`includes()` メソッドが関数の [arguments](/ja/docs/Web/JavaScript/Reference/Functions/arguments) オブジェクトに対して使用される様子を示しています。 + +```js +(function() { + console.log(Array.prototype.includes.call(arguments, 'a')) // true + console.log(Array.prototype.includes.call(arguments, 'd')) // false +})('a','b','c') +``` + +## 仕様書 + +{{Specifications}} + +## ブラウザーの互換性 + +{{Compat}} + +## 関連情報 + +- `Array.prototype.includes` のポリフィルは [`core-js`](https://github.com/zloirock/core-js#ecmascript-array) で利用できます +- {{jsxref("TypedArray.prototype.includes()")}} +- {{jsxref("String.prototype.includes()")}} +- {{jsxref("Array.prototype.indexOf()")}} +- {{jsxref("Array.prototype.find()")}} +- {{jsxref("Array.prototype.findIndex()")}} diff --git a/files/ja/web/javascript/reference/global_objects/array/reduceright/index.html b/files/ja/web/javascript/reference/global_objects/array/reduceright/index.html deleted file mode 100644 index 4d1055ccab..0000000000 --- a/files/ja/web/javascript/reference/global_objects/array/reduceright/index.html +++ /dev/null @@ -1,351 +0,0 @@ ---- -title: Array.prototype.reduceRight() -slug: Web/JavaScript/Reference/Global_Objects/Array/reduceRight -tags: - - Array - - ECMAScript 5 - - JavaScript - - Method - - Prototype - - polyfill -translation_of: Web/JavaScript/Reference/Global_Objects/Array/ReduceRight ---- -<div>{{JSRef}}</div> - -<p><code><strong>reduceRight()</strong></code> メソッドは、隣り合う 2 つの配列要素に対して (右から左へ) 関数を適用して、単一の値にします。</p> - -<div>{{EmbedInteractiveExample("pages/js/array-reduce-right.html","shorter")}}</div> - -<div class="hidden">このデモのソースファイルは GitHub リポジトリに格納されています。デモプロジェクトに協力したい場合は、<a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> をクローンしてプルリクエストを送信してください。</div> - -<p>左から右へ適用する際は {{jsxref("Array.prototype.reduce()")}} を参照してください。</p> - -<h2 id="Syntax" name="Syntax">構文</h2> - -<pre class="syntaxbox notranslate"><var>arr</var>.reduceRight(<var>callback</var>(<var>accumulator</var>, <var>currentValue</var>[, <var>index</var>[, <var>array</var>]])[, <var>initialValue</var>])</pre> - -<h3 id="Parameters" name="Parameters">引数</h3> - -<dl> - <dt><code><var>callback</var></code></dt> - <dd>4 つの引数を取って、配列内の各値に対し実行するコールバック関数 - <dl> - <dt><code><var>accumulator</var></code></dt> - <dd>現在処理されている配列要素の 1 つ前の要素。もしくは、指定されていれば <code><var>initialValue</var></code>。(下記参照)</dd> - <dt><code><var>currentValue</var></code></dt> - <dd>現在処理されている配列要素</dd> - <dt><code><var>index</var></code>{{optional_inline}}</dt> - <dd>現在処理されている配列要素のインデックス</dd> - <dt><code><var>array</var></code>{{optional_inline}}</dt> - <dd><code>reduceRight()</code> によって呼ばれる配列</dd> - </dl> - </dd> - <dt><code><var>initialValue</var></code> {{optional_inline}}</dt> - <dd><code><var>callback</var></code> の最初の呼び出しのときに、最初の実引数として用いるためのオブジェクト。initialValue が渡されなかった際は、配列の最後の要素が適用されます。また、空の配列に対して、初期値なしで呼び出すと <code>TypeError</code> になります。</dd> -</dl> - -<h3 id="Return_value" name="Return_value">返値</h3> - -<p>畳み込みによって得られた 1 つの値です。</p> - -<h2 id="Description" name="Description">解説</h2> - -<p><code>reduceRight</code> は、配列に存在する各要素に対して、<code>callback</code> 関数を一度だけ実行します。配列における穴は対象からはずされ、初期値(あるいは、直前の <code>callback</code> 呼び出し)、現在の要素の値、現在のインデックス、繰り返しが行われる配列の 4 つの引数を受け取ります。</p> - -<p>reduceRight の <code><var>callback</var></code> の呼び出しは、以下のように見えるでしょう。</p> - -<pre class="brush: js notranslate">array.reduceRight(function(accumulator, currentValue, index, array) { - // ... -}); -</pre> - -<p>関数が初めて呼び出されたとき、<code><var>accumulator</var></code> と <code><var>currentValue</var></code> は、2 つの値のいずれかになります。<code>reduceRight</code> の呼び出しで <code><var>initialValue</var></code> が指定された場合、<code><var>accumulator</var></code> は <code><var>initialValue</var></code> と等しくなり、<code><var>currentValue</var></code> は配列の最後の値と等しくなります。<code><var>initialValue</var></code> が指定されなかった場合、<code><var>accumulator</var></code> は配列の最後の値に等しく、<code><var>currentValue</var></code> は最後から 2 番目の値に等しくなります。</p> - -<p>配列が空で、<code><var>initialValue</var></code> が指定されていない場合、{{jsxref("TypeError")}} が投げられます。配列に要素が 1 つしかなく(位置に関係なく)、<code><var>initialValue</var></code> が指定されていない場合、または <code><var>initialValue</var></code> が指定されているが配列が空の場合、<code><var>callback</var></code> を呼び出さずに単独の値が返されます。</p> - -<p>この関数を使用した場合について見てみましょう。</p> - -<pre class="brush: js notranslate">[0, 1, 2, 3, 4].reduceRight(function(accumulator, currentValue, index, array) { - return accumulator + currentValue; -}); -</pre> - -<p>コールバックは 4 回呼び出され、各コールの引数と戻り値は以下のようになります。</p> - -<table> - <thead> - <tr> - <th scope="col"><code><var>callback</var></code></th> - <th scope="col"><code><var>accumulator</var></code></th> - <th scope="col"><code><var>currentValue</var></code></th> - <th scope="col"><code><var>index</var></code></th> - <th scope="col"><code><var>array</var></code></th> - <th scope="col">return value</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">2 回目の呼出し</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">3 回目の呼出し</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">4 回目の呼出し</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>10</code>) になります。</p> - -<p><code>initialValue</code> を与えた場合、その結果は以下のようになります。</p> - -<pre class="brush: js notranslate">[0, 1, 2, 3, 4].reduceRight(function(accumulator, currentValue, index, array) { - return accumulator + currentValue; -}, 10); -</pre> - -<table> - <thead> - <tr> - <th scope="col"><code><var>callback</var></code></th> - <th scope="col"><code><var>accumulator</var></code></th> - <th scope="col"><code><var>currentValue</var></code></th> - <th scope="col"><code><var>index</var></code></th> - <th scope="col"><code><var>array</var></code></th> - <th scope="col">return value</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">2 回目の呼出し</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">3 回目の呼出し</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">4 回目の呼出し</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">5 回目の呼出し</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="Polyfill" name="Polyfill">ポリフィル</h2> - -<p><code>reduceRight</code> は ECMA-262 の第5版に追加されたもので、すべての実装には存在しない可能性があります。これを回避するには、スクリプトの最初に次のコードを挿入して、ネイティブにはサポートされていない実装でも <code>reduceRight</code> を使用できるようにします。</p> - -<pre class="brush: js notranslate">// Production steps of ECMA-262, Edition 5, 15.4.4.22 -// Reference: 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="Examples" name="Examples">例</h2> - -<h3 id="Sum_up_all_values_within_an_array" name="Sum_up_all_values_within_an_array">配列内のすべての値を合計する</h3> - -<pre class="brush: js notranslate">var sum = [0, 1, 2, 3].reduceRight(function(a, b) { - return a + b; -}); -// sum is 6 -</pre> - -<h3 id="Flatten_an_array_of_arrays" name="Flatten_an_array_of_arrays">配列中の配列を平坦化する</h3> - -<pre class="brush: js notranslate">var flattened = [[0, 1], [2, 3], [4, 5]].reduceRight(function(a, b) { - return a.concat(b); -}, []); -// flattened is [4, 5, 2, 3, 0, 1] - -</pre> - -<h3 id="Run_a_list_of_asynchronous_functions_with_callbacks_in_series_each_passing_their_results_to_the_next" name="Run_a_list_of_asynchronous_functions_with_callbacks_in_series_each_passing_their_results_to_the_next">一連のコールバックを使用して非同期関数のリストを実行し、それぞれの結果を次のコールバックに渡す</h3> - -<pre class="brush: js notranslate">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 - -// same as: - -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="Difference_between_reduce_and_reduceRight" name="Difference_between_reduce_and_reduceRight"><code>reduce</code> と <code>reduceRight</code> の違い</h3> - -<pre class="brush: js notranslate">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="Defining_Composible_Function" name="Defining_Composible_Function">関数合計の定義</h3> - -<p>関数合成のコンセプトはシンプルで、n個の関数を組み合わせたものです。これは右から左へと流れ、最後の関数の出力を使用して各関数を呼び出します。</p> - -<pre class="brush: js notranslate">/** - * Function Composition is way in which result of one function can - * be passed to another and so on. - * - * h(x) = f(g(x)) - * - * Function execution happens right to left - * - * https://en.wikipedia.org/wiki/Function_composition - */ - -const compose = (...args) => (value) => args.reduceRight((acc, fn) => fn(acc), value) - -// Increment passed number -const inc = (n) => n + 1 - -// Doubles the passed value -const double = (n) => n * 2 - -// using composition function -console.log(compose(double, inc)(2)); // 6 - -// using composition function -console.log(compose(inc, double)(2)); // 5 -</pre> - -<h2 id="Specifications" name="Specifications">仕様</h2> - -<table class="standard-table"> - <thead> - <tr> - <th scope="col">仕様書</th> - </tr> - </thead> - <tbody> - <tr> - <td>{{SpecName('ESDraft', '#sec-array.prototype.reduceright', 'Array.prototype.reduceRight')}}</td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility" name="Browser_compatibility">ブラウザーの互換性</h2> - -<div> -<p>{{Compat("javascript.builtins.Array.reduceRight")}}</p> -</div> - -<h2 id="See_also" name="See_also">関連情報</h2> - -<ul> - <li>{{jsxref("Array.prototype.reduce()")}}</li> -</ul> diff --git a/files/ja/web/javascript/reference/global_objects/array/reduceright/index.md b/files/ja/web/javascript/reference/global_objects/array/reduceright/index.md new file mode 100644 index 0000000000..04be78ad80 --- /dev/null +++ b/files/ja/web/javascript/reference/global_objects/array/reduceright/index.md @@ -0,0 +1,369 @@ +--- +title: Array.prototype.reduceRight() +slug: Web/JavaScript/Reference/Global_Objects/Array/reduceRight +tags: + - Array + - ECMAScript 5 + - JavaScript + - メソッド + - プロトタイプ + - ポリフィル +browser-compat: javascript.builtins.Array.reduceRight +translation_of: Web/JavaScript/Reference/Global_Objects/Array/ReduceRight +--- +{{JSRef}} + +**`reduceRight()`** メソッドは、アキュームレーターと配列のそれぞれの値に対して (右から左へ) 関数を適用して、単一の値にします。 + +{{EmbedInteractiveExample("pages/js/array-reduce-right.html","shorter")}} + +左から右へ適用する際は {{jsxref("Array.prototype.reduce()")}} を参照してください。 + +## 構文 + +```js +// アロー関数 +reduceRight((accumulator, currentValue) => { ... } ) +reduceRight((accumulator, currentValue, index) => { ... } ) +reduceRight((accumulator, currentValue, index, array) => { ... } ) +reduceRight((accumulator, currentValue, index, array) => { ... }, initialValue) + +// コールバック関数 +reduceRight(callbackFn) +reduceRight(callbackFn, initialValue) + +// コールバック畳み込み関数 +reduceRight(function callbackFn(accumulator, currentValue) { ... }) +reduceRight(function callbackFn(accumulator, currentValue, index) { ... }) +reduceRight(function callbackFn(accumulator, currentValue, index, array){ ... }) +reduceRight(function callbackFn(accumulator, currentValue, index, array) { ... }, initialValue) +``` + +### 引数 + +- `callbackFn` + - : 配列内のそれぞれの値に対して実行するコールバック関数であり、 4 つの引数を取ります。 + - `accumulator` + - : コールバック関数の前回の呼び出しで返された値、もしくは、指定されていれば `initialValue` です。(下記参照) + - `currentValue` + - : 配列内で現在処理中の要素です。 + - `index`{{optional_inline}} + - : 配列内で現在処理中の要素の位置です。 + - `array`{{optional_inline}} + - : `reduceRight()` が呼び出された配列です。 + +- `initialValue` {{optional_inline}} + - : `callbackFn` の最初の呼び出しのときに、アキュームレーターとして使用する値です。初期値がが渡されなかった場合は、配列の最後の要素が適用され、その要素が飛ばされます。また、 reduce または reduceRight を空の配列に対して初期値なしで呼び出すと `TypeError` になります。 + +### 返値 + +畳み込みによって得られた値です。 + +## 解説 + +`reduceRight` は、配列内に存在するそれぞれの要素に対してコールバック関数を一度ずつ実行します。配列内の穴は対象外です。初期値 (あるいは直前のコールバックの呼び出し結果)、現在の要素の値、現在の位置、繰り返しが行われる配列の 4 つの引数を受け取ります。 + +reduceRight の `callbackFn` の呼び出しは、以下のように見えるでしょう。 + +```js +arr.reduceRight(function(accumulator, currentValue, index, array) { + // ... +}); +``` + +関数が初めて呼び出されたとき、`accumulator` と `currentValue` は、2 つの値のいずれかになります。 `initialValue` を指定して `reduceRight` を呼び出した場合、`accumulator` は `initialValue` と等しくなり、`currentValue` は配列の最後の値と等しくなります。`initialValue` が指定されなかった場合、`accumulator` は配列の最後の値に等しく、`currentValue` は最後から 2 番目の値に等しくなります。 + +配列が空で、`initialValue` が指定されなかった場合は、{{jsxref("TypeError")}} が発生します。配列に (位置に関わらず) 要素が 1 つしかなく、`initialValue` が指定されなかった場合、または `initialValue` が指定されたが配列が空だった場合は、`callbackFn` を呼び出されずに単独の値が返されます。 + +この関数を使用した場合について見てみましょう。 + +```js +[0, 1, 2, 3, 4].reduceRight(function(accumulator, currentValue, index, array) { + return accumulator + currentValue; +}); +``` + +コールバックは 4 回呼び出され、ぞれぞれの呼び出しの引数と返値は次のようになります。 + +<table> + <thead> + <tr> + <th scope="col"> + <code><var>callback</var></code> + </th> + <th scope="col"> + <code><var>accumulator</var></code> + </th> + <th scope="col"> + <code><var>currentValue</var></code> + </th> + <th scope="col"> + <code><var>index</var></code> + </th> + <th scope="col"> + <code><var>array</var></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">2 回目の呼び出し</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">3 回目の呼び出し</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">4 回目の呼び出し</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> + +`reduceRight` の返値は、コールバック呼び出しの最後の返値である (`10`) になります。 + +`initialValue` を渡した場合、結果は次のようになります。 + +```js +[0, 1, 2, 3, 4].reduceRight(function(accumulator, currentValue, index, array) { + return accumulator + currentValue; +}, 10); +``` + +<table> + <thead> + <tr> + <th scope="col"> + <code><var>callback</var></code> + </th> + <th scope="col"> + <code><var>accumulator</var></code> + </th> + <th scope="col"> + <code><var>currentValue</var></code> + </th> + <th scope="col"> + <code><var>index</var></code> + </th> + <th scope="col"> + <code><var>array</var></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">2 回目の呼び出し</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">3 回目の呼び出し</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">4 回目の呼び出し</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">5 回目の呼び出し</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> + +この場合の `reduceRight` の返値は `20` になります。 + +## ポリフィル + +`reduceRight` は ECMA-262 の第 5 版に追加されたもので、すべての実装には存在しない可能性があります。これを回避するには、スクリプトの最初に次のコードを挿入して、ネイティブには対応していない実装でも `reduceRight` を使用できるようにします。 + +```js +// Production steps of ECMA-262, Edition 5, 15.4.4.22 +// Reference: https://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; + }; +} +``` + +## 例 + +### 配列内のすべての値を合計する + +```js +var sum = [0, 1, 2, 3].reduceRight(function(a, b) { + return a + b; +}); +// sum is 6 +``` + +### 配列中の配列を平坦化する + +```js +var flattened = [[0, 1], [2, 3], [4, 5]].reduceRight(function(a, b) { + return a.concat(b); +}, []); +// flattened is [4, 5, 2, 3, 0, 1] +``` + +### 一連のコールバックを使用して非同期関数のリストを実行し、それぞれの結果を次のコールバックに渡す + +```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 + +// same as: + +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); +} +``` + +### `reduce` と `reduceRight` の違い + +```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" +``` + +### 合成可能な関数の定義 + +関数合成とは、各関数の出力を次の関数に渡し、最後の関数の出力を最終的な結果とする、関数を組み合わせるための仕組みです。この例では `reduceRight()` を使って、関数合成を実現しています。 + +Wikipedia の [Function composition](<https://en.wikipedia.org/wiki/Function_composition_(computer_science)>) も参照してください。 + +```js +const compose = (...args) => (value) => args.reduceRight((acc, fn) => fn(acc), value) + +// 渡された数値をインクリメントする +const inc = (n) => n + 1 + +// 渡された数値を 2 倍にする +const double = (n) => n * 2 + +// 合成関数を使用する +console.log(compose(double, inc)(2)); // 6 + +// 合成関数を使用する +console.log(compose(inc, double)(2)); // 5 +``` + +## 仕様書 + +{{Specifications}} + +## ブラウザーの互換性 + +{{Compat}} + +## 関連情報 + +- `Array.prototype.reduceRight` のポリフィルが [`core-js`](https://github.com/zloirock/core-js#ecmascript-array) で利用できます +- {{jsxref("Array.prototype.reduce()")}} |
