diff options
Diffstat (limited to 'files/ja/web/javascript/reference/operators')
79 files changed, 10412 insertions, 0 deletions
diff --git a/files/ja/web/javascript/reference/operators/addition/index.html b/files/ja/web/javascript/reference/operators/addition/index.html new file mode 100644 index 0000000000..d87d6a2894 --- /dev/null +++ b/files/ja/web/javascript/reference/operators/addition/index.html @@ -0,0 +1,82 @@ +--- +title: 加算 (+) +slug: Web/JavaScript/Reference/Operators/Addition +tags: + - JavaScript + - Language feature + - Operator + - Reference +translation_of: Web/JavaScript/Reference/Operators/Addition +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>加算演算子 (<code>+</code>) は、数値オペランドまたは文字列連結の合計を生成します。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-addition.html")}}</div> + +<div></div> + + + +<h2 id="構文">構文</h2> + +<pre class="syntaxbox notranslate"><strong>Operator:</strong> <var>x</var> + <var>y</var> +</pre> + +<h2 id="例">例</h2> + +<h3 id="数値加算">数値加算</h3> + +<pre class="brush: js notranslate">// 数値 + 数値 -> 加算 +1 + 2 // 3 + +// ブール値 + 数値 -> 加算 +true + 1 // 2 + +// ブール値 + ブール値 -> 加算 +false + false // 0 +</pre> + +<h3 id="文字列連結">文字列連結</h3> + +<pre class="brush: js notranslate">// 文字列 + 文字列 -> 連結 +'foo' + 'bar' // "foobar" + +// 数値 + 文字列 -> 連結 +5 + 'foo' // "5foo" + +// 文字列 + ブール値 -> 連結 +'foo' + false // "foofalse"</pre> + +<h2 id="仕様">仕様</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">仕様</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-addition-operator-plus', 'Addition operator')}}</td> + </tr> + </tbody> +</table> + +<h2 id="ブラウザーの互換性">ブラウザーの互換性</h2> + + + +<p>{{Compat("javascript.operators.addition")}}</p> + +<h2 id="関連項目">関連項目</h2> + +<ul> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Subtraction">減算演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Division">除算演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Multiplication">乗算演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Remainder">剰余演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Exponentiation">べき乗演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Increment">インクリメント演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Decrement">デクリメント演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Unary_negation">単項マイナス演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Unary_plus">単項プラス演算子</a></li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/addition_assignment/index.html b/files/ja/web/javascript/reference/operators/addition_assignment/index.html new file mode 100644 index 0000000000..d2e2a59492 --- /dev/null +++ b/files/ja/web/javascript/reference/operators/addition_assignment/index.html @@ -0,0 +1,78 @@ +--- +title: 加算代入 (+=) +slug: Web/JavaScript/Reference/Operators/Addition_assignment +tags: + - Assignment operator + - JavaScript + - Language feature + - Operator + - Reference +translation_of: Web/JavaScript/Reference/Operators/Addition_assignment +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>加算代入演算子 (<code>+=</code>) は、右辺のオペランドの値を変数に加算し、結果を変数に代入します。 2つのオペランドの型は、加算代入演算子の動作を決定します。加算もしくは連結が可能です。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-addition-assignment.html")}}</div> + +<div></div> + + + +<h2 id="構文">構文</h2> + +<pre class="syntaxbox notranslate"><strong>Operator:</strong> x += y +<strong>Meaning:</strong> x = x + y</pre> + +<h2 id="例">例</h2> + +<h3 id="加算代入の使用">加算代入の使用</h3> + +<pre class="brush: js notranslate">// 以下の変数を想定 +// foo = 'foo' +// bar = 5 +// baz = true + +// 数値 + 数値 -> 加算 +bar += 2 // 7 + +// ブール値 + 数値 -> 加算 +baz += 1 // 2 + +// ブール値 + ブール値 -> 加算 +baz += false // 1 + +// 数値 + 文字列 -> 連結 +bar += 'foo' // "5foo" + +// 文字列 + ブール値 -> 連結 +foo += false // "foofalse" + +// 文字列 + 文字列 -> 連結 +foo += 'bar' // "foobar"</pre> + +<h2 id="仕様">仕様</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">仕様</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-assignment-operators', 'Assignment operators')}}</td> + </tr> + </tbody> +</table> + +<h2 id="ブラウザーの互換性">ブラウザーの互換性</h2> + + + +<p>{{Compat("javascript.operators.addition_assignment")}}</p> + +<h2 id="関連項目">関連項目</h2> + +<ul> + <li><a href="/docs/Web/JavaScript/Guide/Expressions_and_Operators#Assignment">代入演算子</a></li> + <li><a href="/docs/Web/JavaScript/Reference/Operators/Addition">加算演算子</a></li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/array_comprehensions/index.html b/files/ja/web/javascript/reference/operators/array_comprehensions/index.html new file mode 100644 index 0000000000..814bdd9eb7 --- /dev/null +++ b/files/ja/web/javascript/reference/operators/array_comprehensions/index.html @@ -0,0 +1,198 @@ +--- +title: 配列内包表記 +slug: Web/JavaScript/Reference/Operators/Array_comprehensions +tags: + - JavaScript + - Non-standard + - Operator + - Reference +translation_of: Archive/Web/JavaScript/Array_comprehensions +--- +<div class="warning"><strong>非標準。使用しないでください!</strong><br> +配列内包は非標準であり、Firefox 58 から削除されています。将来向きの用途には、{{jsxref("Array.prototype.map")}}、{{jsxref("Array.prototype.filter")}}、{{jsxref("Functions/Arrow_functions", "アロー関数", "", 1)}}、{{jsxref("Operators/Spread_operator", "スプレッド構文", "", 1)}} の使用を検討してください。</div> + +<div>{{jsSidebar("Operators")}}</div> + +<p><strong>array comprehension</strong> 構文は、既存のものに基づいている新しい配列をすばやく組み立てることができるJavaScriptの式でした。しかし、これは標準仕様や Firefox の実装から削除されました。使用しないでください!</p> + +<h2 id="構文">構文</h2> + +<pre class="syntaxbox">[for (x of iterable) x] +[for (x of iterable) if (condition) x] +[for (x of iterable) for (y of iterable) x + y] +</pre> + +<h2 id="説明">説明</h2> + +<p>配列の内包表記内で、下記の二種類のコンポーネントが許されています。:</p> + +<ul> + <li>{{jsxref("Statements/for...of", "for...of")}}</li> + <li>{{jsxref("Statements/if...else", "if")}}</li> +</ul> + +<p>for-of イテレーションは常に最初のコンポーネントです。複数のfor-of イテレーションは、ステートメントが許可されている場合。</p> + +<p>配列内包は以前、ECMAScript 2016 で標準化を提案されていました。これは別のものに基づいて新たな配列を構成するための手っ取り早い方法を提供します。配列内包は一般に、{{jsxref("Array.prototype.map", "map()")}} および {{jsxref("Array.prototype.filter", "filter()")}} を呼び出す代わりとして、あるいはそれら 2 つを結合する手段として用いることができます。</p> + +<p>次の配列内包は数値の配列を取り込んで、その各数値を 2 倍した値による新しい配列を作成します。</p> + +<pre class="brush: js">var numbers = [1, 2, 3, 4]; +var doubled = [for (i of numbers) i * 2]; +console.log(doubled); // logs 2,4,6,8 +</pre> + +<p>これは以下の {{jsxref("Array.prototype.map", "map()")}} による操作と同等です:</p> + +<pre class="brush: js">var doubled = numbers.map(i => i * 2); +</pre> + +<p>配列内包は、特定の式にマッチするアイテムの選択に用いることもできます。以下は、偶数だけを選択する内包です:</p> + +<pre class="brush: js">var numbers = [1, 2, 3, 21, 22, 30]; +var evens = [for (i of numbers) if (i % 2 === 0) i]; +console.log(evens); // logs 2,22,30 +</pre> + +<p>同じ目的で {{jsxref("Array.prototype.filter", "filter()")}} を用いることができます:</p> + +<pre class="brush: js">var evens = numbers.filter(i => i % 2 === 0); +</pre> + +<p>{{jsxref("Array.prototype.map", "map()")}} および {{jsxref("Array.prototype.filter", "filter()")}} 方式の操作を、ひとつの配列内包に統合することができます。以下は偶数だけをフィルタリングして、それらを 2 倍した値を含む配列を作成します:</p> + +<pre class="brush: js">var numbers = [1, 2, 3, 21, 22, 30]; +var doubledEvens = [for (i of numbers) if (i % 2 === 0) i * 2]; +console.log(doubledEvens); // logs 4,44,60 +</pre> + +<p>配列内包の角括弧は、スコープ目的の暗黙的なブロックをもたらします。新しい変数 (上記の例における i ) は、{{jsxref("Statements/let","let")}} を用いて宣言されたかのように扱われます。つまり、それらの変数は配列内包の外部で使用できません。</p> + +<p>配列内包の入力自体は、配列である必要はありません。<a href="/ja/docs/Web/JavaScript/Guide/Iterators_and_Generators" title="JavaScript/Guide/Iterators and Generators">イテレータおよびジェネレータ</a> も使用できます。</p> + +<p>文字列を入力とすることもできます。(配列状のオブジェクトにおいて) 前出の filter や map の動作を実現するには以下のようにします:</p> + +<pre class="brush: js">var str = 'abcdef'; +var consonantsOnlyStr = [for (c of str) if (!(/[aeiouAEIOU]/).test(c)) c].join(''); // 'bcdf' +var interpolatedZeros = [for (c of str) c + '0' ].join(''); // 'a0b0c0d0e0f0' +</pre> + +<p>繰り返しになりますが入力データの形式は維持されませんので、文字列へ戻すために {{jsxref("Array.prototype.join", "join()")}} を使用しなければなりません。</p> + +<h2 id="例">例</h2> + +<h3 id="簡単な配列の内包表記">簡単な配列の内包表記</h3> + +<pre class="brush:js">[for (i of [ 1, 2, 3 ]) i*i ]; +// [ 1, 4, 9 ] + +var abc = [ "A", "B", "C" ]; +[for (letters of abc) letters.toLowerCase()]; +// [ "a", "b", "c" ]</pre> + +<h3 id="if文で配列の内包表記">if文で配列の内包表記</h3> + +<pre class="brush: js">var years = [ 1954, 1974, 1990, 2006, 2010, 2014 ]; +[for (year of years) if (year > 2000) year]; +// [ 2006, 2010, 2014 ] +[for (year of years) if (year > 2000) if(year < 2010) year]; +// [ 2006], the same as below: +[for (year of years) if (year > 2000 && year < 2010) year]; +// [ 2006] +</pre> + +<h3 id="mapとfilterを比較する配列の内包表記"><code>map</code>と<code>filter</code>を比較する配列の内包表記</h3> + +<p>配列の内包表記構文を理解する簡単な方法は、Array {{jsxref("Array.map", "map")}}や{{jsxref("Array.filter", "filter")}}メソッドと比較することです。:</p> + +<pre class="brush: js">var numbers = [ 1, 2, 3 ]; + +numbers.map(function (i) { return i * i }); +numbers.map(i => i*i); +[for (i of numbers) i*i ]; +// all are [ 1, 4, 9 ] + +numbers.filter(function (i) { return i < 3 }); +numbers.filter(i => i < 3); +[for (i of numbers) if (i < 3) i]; +// all are [ 1, 2 ] +</pre> + +<h3 id="二つの配列の内包表記">二つの配列の内包表記</h3> + +<p>二つの配列で動作させるために二つのfor-ofイテレーションを使用する:</p> + +<pre class="brush: js">var numbers = [ 1, 2, 3 ]; +var letters = [ "a", "b", "c" ]; + +var cross = [for (i of numbers) for (j of letters) i+j]; +// [ "1a", "1b", "1c", "2a", "2b", "2c", "3a", "3b", "3c" ] + +var grid = [for (i of numbers) [for (j of letters) i+j]]; +// [ +// ["1a", "1b", "1c"], +// ["2a", "2b", "2c"], +// ["3a", "3b", "3c"] +// ] + +[for (i of numbers) if (i > 1) for (j of letters) if(j > "a") i+j] +// ["2b", "2c", "3b", "3c"], the same as below: + +[for (i of numbers) for (j of letters) if (i > 1) if(j > "a") i+j] +// ["2b", "2c", "3b", "3c"] + +[for (i of numbers) if (i > 1) [for (j of letters) if(j > "a") i+j]] +// [["2b", "2c"], ["3b", "3c"]], not the same as below: + +[for (i of numbers) [for (j of letters) if (i > 1) if(j > "a") i+j]] +// [[], ["2b", "2c"], ["3b", "3c"]] +</pre> + +<h2 id="Specifications" name="Specifications">仕様</h2> + +<p>最初は ECMAScript 2015 のドラフトでしたが、リビジョン 27 (2014 年 8 月) で取り除かれました。仕様セマンティクスのために ES2015 の古いリビジョンを参照してください。</p> + +<h2 id="Browser_compatibility" name="Browser_compatibility">ブラウザー実装状況</h2> + + + +<p>{{Compat("javascript.operators.array_comprehensions")}}</p> + +<h2 id="Differences_to_the_older_JS1.7JS1.8_comprehensions" name="Differences_to_the_older_JS1.7JS1.8_comprehensions">古い JS1.7/JS1.8 の内包表記との違い</h2> + +<div class="warning">JS1.7/JS1.8 の内包表記は、バージョン 46 で Gecko から削除しました ({{bug(1220564)}})。</div> + +<p><strong>古い内包表記の構文 (使用しないでください!):</strong></p> + +<pre class="brush: js example-bad">[X for (Y in Z)] +[X for each (Y in Z)] +[X for (Y of Z)] +</pre> + +<p>違い:</p> + +<ul> + <li>ESNext の内包表記は全体の内包表記のかわりに"for"ノードごとに1スコープを生成します。 + <ul> + <li>旧: <code>[()=>x for (x of [0, 1, 2])][1]() // 2</code></li> + <li>新: <code>[for (x of [0, 1, 2]) ()=>x][1]() // 1, each iteration creates a fresh binding for x. </code></li> + </ul> + </li> + <li>ESNext の内包表記は代入式のかわりに"for"で始まります。 + <ul> + <li>旧: <code>[i * 2 for (i of numbers)]</code></li> + <li>新: <code>[for (i of numbers) <code>i * 2</code>]</code></li> + </ul> + </li> + <li>ESNext の内包表記は複数の<code>if</code>と<code>for</code>コンポーネントを持ち得ます。</li> + <li>ESNext の内包表記は<code>{{jsxref("Statements/for...of", "for...of")}}</code>でのみ動作し、<code>{{jsxref("Statements/for...in", "for...in")}}</code>イテレーションで 動作しません。</li> +</ul> + +<p>コード更新の提案について、<a href="https://bugzilla.mozilla.org/show_bug.cgi?id=1220564#c42">Bug 1220564 のコメント 42</a> をご覧ください。</p> + +<h2 id="関連情報">関連情報</h2> + +<ul> + <li>{{jsxref("Statements/for...of", "for...of")}}</li> + <li>{{jsxref("Operators/Generator_comprehensions", "Generator comprehensions", "" ,1)}}</li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/assignment/index.html b/files/ja/web/javascript/reference/operators/assignment/index.html new file mode 100644 index 0000000000..acf35e7514 --- /dev/null +++ b/files/ja/web/javascript/reference/operators/assignment/index.html @@ -0,0 +1,62 @@ +--- +title: 代入 (=) +slug: Web/JavaScript/Reference/Operators/Assignment +tags: + - Assignment operator + - JavaScript + - Language feature + - Operator + - Reference +translation_of: Web/JavaScript/Reference/Operators/Assignment +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>代入(単純代入)演算子 (<code>=</code>) は、変数に値を代入するために使用されます。割り当て操作は、割り当てられた値を評価します。 単一の値を複数の変数に割り当てるため、代入演算子の連鎖が可能です。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-assignment.html")}}</div> + +<div></div> + + + +<h2 id="構文">構文</h2> + +<pre class="syntaxbox notranslate"><strong>Operator:</strong> x = y +</pre> + +<h2 id="例">例</h2> + +<h3 id="代入と連鎖">代入と連鎖</h3> + +<pre class="brush: js notranslate">// 以下の変数を想定 +// x = 5 +// y = 10 +// z = 25 + +x = y // x は 10 +x = y = z // x, y そして z は全て 25</pre> + +<h2 id="仕様">仕様</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">仕様書</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-assignment-operators', 'Assignment operators')}}</td> + </tr> + </tbody> +</table> + +<h2 id="ブラウザーの互換性">ブラウザーの互換性</h2> + + + +<p>{{Compat("javascript.operators.assignment")}}</p> + +<h2 id="関連項目">関連項目</h2> + +<ul> + <li><a href="/docs/Web/JavaScript/Guide/Expressions_and_Operators#Assignment">代入演算子</a></li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/async_function/index.html b/files/ja/web/javascript/reference/operators/async_function/index.html new file mode 100644 index 0000000000..f6b13ca9f2 --- /dev/null +++ b/files/ja/web/javascript/reference/operators/async_function/index.html @@ -0,0 +1,151 @@ +--- +title: 非同期関数式 +slug: Web/JavaScript/Reference/Operators/async_function +tags: + - Experimental + - Function + - JavaScript + - Operator + - Primary Expression +translation_of: Web/JavaScript/Reference/Operators/async_function +--- +<div>{{jsSidebar("Operators")}}</div> + +<p><strong><code>async function</code></strong> キーワードは、式内で async function を定義するために使用できます。</p> + +<h2 id="構文">構文</h2> + +<pre class="syntaxbox">async function [<em>name</em>]([<em>param1</em>[, <em>param2[</em>, ..., <em>paramN</em>]]]) { + <em>statements</em> +}</pre> + +<h3 id="引数">引数</h3> + +<dl> + <dt><code>name</code></dt> + <dd>関数名。関数が<em>匿名</em>の場合、省略可能。名前は関数ボディー内のみのローカル。</dd> + <dt><code>paramN</code></dt> + <dd>関数に渡される引数名。</dd> + <dt><code>statements</code></dt> + <dd>関数ボディーを構成するステートメント。</dd> +</dl> + +<h2 id="説明">説明</h2> + +<p><code>async function</code> 式は {{jsxref('Statements/async_function', 'async function statement')}} と非常に似ており、構文もほとんど同じです。async <code>function</code> 式と async <code>function</code> ステートメントの主な違いは、<code>async function</code> 式は<em>匿名</em>関数を生成するために<em>関数名</em>を省略できる点です。<code>async function</code> 式は、定義後直ちに実行される <strong>IIFE</strong>(即時実行関数式)として使用することもできます。詳細は <a href="/ja/docs/Web/JavaScript/Reference/Functions">function</a> の章を見てください。</p> + +<h2 id="例">例</h2> + +<h3 id="シンプルな例">シンプルな例</h3> + +<pre class="brush: js">function resolveAfter2Seconds(x) { + return new Promise(resolve => { + setTimeout(() => { + resolve(x); + }, 2000); + }); +}; + +(async function(x) { // async function expression used as an IIFE + var a = resolveAfter2Seconds(20); + var b = resolveAfter2Seconds(30); + return x + await a + await b; +})(10).then(v => { + console.log(v); // prints 60 after 2 seconds. +}); + +var add = async function(x) { // async function expression assigned to a variable + var a = await resolveAfter2Seconds(20); + var b = await resolveAfter2Seconds(30); + return x + a + b; +}; + +add(10).then(v => { + console.log(v); // prints 60 after 4 seconds. +}); +</pre> + +<h2 id="仕様">仕様</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">仕様</th> + <th scope="col">ステータス</th> + <th scope="col">コメント</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('Async Function', '#async-function-definitions', 'async function')}}</td> + <td>{{Spec2('Async Function')}}</td> + <td>提案</td> + </tr> + </tbody> +</table> + +<h2 id="ブラウザー実装状況">ブラウザー実装状況</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>機能</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th> Edge</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>基本サポート</td> + <td>{{CompatChrome(55)}}</td> + <td>{{CompatGeckoDesktop("52.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatOpera(42)}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>機能</th> + <th>Android</th> + <th>Android Webview</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android</th> + </tr> + <tr> + <td>基本サポート</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("52.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatOpera(42)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatChrome(55)}}</td> + </tr> + </tbody> +</table> +</div> + +<p> </p> + +<h2 id="関連項目">関連項目</h2> + +<ul> + <li>{{jsxref("Statements/async_function", "async function")}}</li> + <li>{{jsxref("AsyncFunction")}} オブジェクト</li> + <li>{{jsxref("Operators/await", "await")}}</li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/await/index.html b/files/ja/web/javascript/reference/operators/await/index.html new file mode 100644 index 0000000000..775ce4a787 --- /dev/null +++ b/files/ja/web/javascript/reference/operators/await/index.html @@ -0,0 +1,139 @@ +--- +title: await +slug: Web/JavaScript/Reference/Operators/await +tags: + - Function + - JavaScript + - Language feature + - Operator + - Primary Expression +translation_of: Web/JavaScript/Reference/Operators/await +--- +<div>{{jsSidebar("Operators")}}</div> + +<p><code>await</code> 演算子は、{{jsxref("Statements/async_function", "async function")}} によって {{jsxref("Promise")}} が返されるのを待機するために使用します。</p> + +<h2 id="Syntax" name="Syntax">構文</h2> + +<pre class="syntaxbox notranslate">[<em>rv</em>] = await <em>expression</em>;</pre> + +<dl> + <dt><code>expression</code></dt> + <dd>解決を待つ {{jsxref("Promise")}} もしくは何らかの値。</dd> + <dt><code>rv</code></dt> + <dd> + <p>解決された promise の値。expression が <code>Promise</code> ではない場合はその値自体を返す。</p> + </dd> +</dl> + +<h2 id="Description" name="Description">説明</h2> + +<p><code>await</code> 式は <code>async</code> function の実行を一時停止し、<code>Promise</code> の解決または拒否を待ちます。解決した後に <code>async</code> function の実行を再開します。再開するときに <code>await</code> 式は解決された <code>Promise</code> にラップされた値を返します。</p> + +<p><code>Promise</code> が拒否された場合、<code>await</code> 式は理由となった値を投げます。</p> + +<p><code>await</code> 式に続く値が <code>Promise</code> ではなかった場合、<a href="/ja/docs/Web/JavaScript/Reference/Global_Objects/Promise/resolve">解決された Promise</a> に変換されます。</p> + +<p><code>await</code> は実行フローを分割できるため、<code>await</code> の関数の呼び出し元は、<code>await</code> の関数の遅延継続の前に実行を再開できます。<code>await</code> がその関数の継続を延期した後、これが関数によって実行される最初の <code>await</code> でれば、<code>await</code> の関数の完了を求める保留中の <code>Promise</code> を関数の呼び出し元に返し、その呼び出し元の実行を再開することによって、即時実行も続行されます。</p> + +<h2 id="Examples" name="Examples">例</h2> + +<h3 id="Awaiting_a_promise_to_be_fulfilled" name="Awaiting_a_promise_to_be_fulfilled">promise の解決を待つ</h3> + +<p><code>Promise</code> が <code>await</code> 式で停止された場合、<code>Promise</code> が解決されて、解決された値を返すのを待ちます。</p> + +<pre class="brush: js notranslate">function resolveAfter2Seconds(x) { + return new Promise(resolve => { + setTimeout(() => { + resolve(x); + }, 2000); + }); +} + +async function f1() { + var x = await resolveAfter2Seconds(10); + console.log(x); // 10 +} + +f1(); +</pre> + +<h3 id="Thenable_objects" name="Thenable_objects">Thenable オブジェクト</h3> + +<p>{{jsxref("Global_Objects/Promise/then", "Thenable オブジェクト")}}もまったく同じように実行されます。</p> + +<pre class="brush: js notranslate">async function f2() { + const thenable = { + then: function(resolve, _reject) { + resolve('resolved!') + } + }; + console.log(await thenable); // resolved! +} + +f2(); +</pre> + +<h3 id="Conversion_to_promise" name="Conversion_to_promise">Promise への変換</h3> + +<p>値が <code>Promise</code> でない場合は、値を解決済みの <code>Promise</code> に変換して待ちます。</p> + +<pre class="brush: js notranslate">async function f3() { + var y = await 20; + console.log(y); // 20 +} + +f3();</pre> + +<h3 id="Promise_rejection" name="Promise_rejection">Promise の拒否</h3> + +<p><code>Promise</code> が拒否された場合、拒否された値が投げられます。</p> + +<pre class="brush: js notranslate">async function f4() { + try { + var z = await Promise.reject(30); + } catch(e) { + console.error(e); // 30 + } +} + +f4();</pre> + +<h3 id="Handling_rejected_promises" name="Handling_rejected_promises">拒否された Promise を処理する</h3> + +<p>拒否された <code>Promise</code> は <code>try</code> 文を使用せずにエラーハンドリングを行えます。</p> + +<pre class="brush: js notranslate">var response = await promisedFunction().catch((err) => { console.error(err); }); +// response will be undefined if the promise is rejected +</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-async-function-definitions", "async functions")}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">ブラウザー実装状況</h2> + +<div> + + +<p>{{Compat("javascript.operators.await")}}</p> +</div> + +<h2 id="See_also" name="See_also">関連情報</h2> + +<ul> + <li>{{jsxref("Statements/async_function", "async function")}}</li> + <li>{{jsxref("Operators/async_function", "async function expression")}}</li> + <li>{{jsxref("AsyncFunction")}} オブジェクト</li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/bitwise_and/index.html b/files/ja/web/javascript/reference/operators/bitwise_and/index.html new file mode 100644 index 0000000000..80a4644aee --- /dev/null +++ b/files/ja/web/javascript/reference/operators/bitwise_and/index.html @@ -0,0 +1,114 @@ +--- +title: ビット論理積 (&) +slug: Web/JavaScript/Reference/Operators/Bitwise_AND +tags: + - Bitwise operator + - JavaScript + - Language feature + - Operator + - Reference + - 演算子 + - 言語機能 +translation_of: Web/JavaScript/Reference/Operators/Bitwise_AND +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>ビット論理積演算子 (<code>&</code>) は、両方のオペランドの対応するビットのいずれもが <code>1</code> である位置のビットで <code>1</code> を返します。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-bitwise-and.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"><code><var>a</var> & <var>b</var></code> +</pre> + +<h2 id="Description" name="Description">解説</h2> + +<p>オペランドは32ビットの整数値に変換され、ビット (ゼロまたは1) の並びによって表現されます。32ビットを超える数値は最上位のビットが破棄されます。例えば、次の32ビットを超える整数は32ビット整数に変換されます。</p> + +<pre class="brush: js notranslate">変換前: 11100110111110100000000000000110000000000001 +変換後: 10100000000000000110000000000001</pre> + +<p>第1オペランドの各ビットは、第2オペランドの対応するビットと組み合わせになります。<em>第1ビット</em>は<em>第1ビット</em>へ、<em>第2ビット</em>は<em>第2ビット</em>へ、という具合にです。</p> + +<p>この演算子は各ビットの組み合わせに適用され、結果はビット単位で構築されます。</p> + +<p>AND 演算の真理値表は次のようになります。</p> + +<table class="standard-table"> + <thead> + <tr> + <th class="header" scope="col">a</th> + <th class="header" scope="col">b</th> + <th class="header" scope="col">a AND b</th> + </tr> + </thead> + <tbody> + <tr> + <td>0</td> + <td>0</td> + <td>0</td> + </tr> + <tr> + <td>0</td> + <td>1</td> + <td>0</td> + </tr> + <tr> + <td>1</td> + <td>0</td> + <td>0</td> + </tr> + <tr> + <td>1</td> + <td>1</td> + <td>1</td> + </tr> + </tbody> +</table> + +<pre class="brush: js notranslate">. 9 (10進数) = 00000000000000000000000000001001 (2進数) + 14 (10進数) = 00000000000000000000000000001110 (2進数) + -------------------------------- +14 | 9 (10進数) = 00000000000000000000000000001000 (2進数) = 8 (10進数) +</pre> + +<p>任意の <code><var>x</var></code> と <code>0</code> のビット論理積は <code>0</code> になります。</p> + +<h2 id="Examples" name="Examples">例</h2> + +<h3 id="Using_bitwise_AND" name="Using_bitwise_AND">ビット論理積の使用</h3> + +<pre class="brush: js notranslate">// 5: 00000000000000000000000000000101 +// 2: 00000000000000000000000000000010 +5 & 2; // 0</pre> + +<h2 id="Specifications" name="Specifications">仕様書</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">仕様書</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#prod-BitwiseANDExpression', 'Bitwise AND expression')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">ブラウザーの互換性</h2> + +<div class="hidden">このページの互換性一覧表は構造化データから生成されています。データに協力していただけるのであれば、 <a class="external" href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> をチェックアウトしてプルリクエストを送信してください。</div> + +<p>{{Compat("javascript.operators.bitwise_and")}}</p> + +<h2 id="See_also" name="See_also">関連情報</h2> + +<ul> + <li><a href="/ja/docs/Web/JavaScript/Guide/Expressions_and_Operators#Bitwise_operators">ビット演算子ガイド</a></li> + <li><a href="/ja/docs/Web/JavaScript/Reference/Operators/Bitwise_AND_assignment">ビット論理積代入演算子</a></li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/bitwise_and_assignment/index.html b/files/ja/web/javascript/reference/operators/bitwise_and_assignment/index.html new file mode 100644 index 0000000000..431e576433 --- /dev/null +++ b/files/ja/web/javascript/reference/operators/bitwise_and_assignment/index.html @@ -0,0 +1,64 @@ +--- +title: ビット論理積代入 (&=) +slug: Web/JavaScript/Reference/Operators/Bitwise_AND_assignment +tags: + - Assignment operator + - JavaScript + - Language feature + - Operator + - Reference + - 代入演算子 + - 演算子 + - 言語機能 +translation_of: Web/JavaScript/Reference/Operators/Bitwise_AND_assignment +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>ビット論理積代入演算子 (<code>&=</code>) は、両方のオペランドのバイナリ表現を使用し、それらに対してビット単位の AND 演算を実行して、結果を変数に代入します。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-bitwise-and-assignment.html")}}</div> + +<div></div> + + + +<h2 id="構文">構文</h2> + +<pre class="syntaxbox notranslate"><strong>Operator:</strong> x &= y +<strong>Meaning:</strong> x = x & y +</pre> + +<h2 id="例">例</h2> + +<h3 id="ビット論理積代入の使用">ビット論理積代入の使用</h3> + +<pre class="brush: js notranslate">let a = 5; +// 5: 00000000000000000000000000000101 +// 2: 00000000000000000000000000000010 +a &= 2; // 0</pre> + +<h2 id="仕様">仕様</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">仕様書</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-assignment-operators', 'Assignment operators')}}</td> + </tr> + </tbody> +</table> + +<h2 id="ブラウザーの互換性">ブラウザーの互換性</h2> + + + +<p>{{Compat("javascript.operators.bitwise_and_assignment")}}</p> + +<h2 id="関連項目">関連項目</h2> + +<ul> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Guide/Expressions_and_Operators#Bitwise_operators">ビット演算子ガイド</a></li> + <li><a href="/ja/docs/Web/JavaScript/Reference/Operators/Bitwise_AND">ビット論理積演算子</a></li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/bitwise_not/index.html b/files/ja/web/javascript/reference/operators/bitwise_not/index.html new file mode 100644 index 0000000000..ddd2d99c4d --- /dev/null +++ b/files/ja/web/javascript/reference/operators/bitwise_not/index.html @@ -0,0 +1,102 @@ +--- +title: ビット否定 (~) +slug: Web/JavaScript/Reference/Operators/Bitwise_NOT +tags: + - Bitwise operator + - JavaScript + - Language feature + - Operator + - Reference + - 演算子 + - 言語機能 +translation_of: Web/JavaScript/Reference/Operators/Bitwise_NOT +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>ビット否定演算子 (<code>~</code>) は、オペランドの各ビットを反転します。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-bitwise-not.html")}}</div> + +<div></div> + + + +<h2 id="構文">構文</h2> + +<pre class="syntaxbox notranslate"><code><var>~a</var></code> +</pre> + +<h2 id="解説">解説</h2> + +<p>オペランドは32ビットの整数値に変換され、ビット (ゼロまたは1) の並びによって表現されます。32ビットを超える数値は最上位のビットが破棄されます。例えば、次の32ビットを超える整数は32ビット整数に変換されます。</p> + +<pre class="brush: js notranslate">変換前: 11100110111110100000000000000110000000000001 +変換後: 10100000000000000110000000000001</pre> + +<p>第1オペランドの各ビットは、第2オペランドの対応するビットと組み合わせになります。<em>第1ビット</em>は<em>第1ビット</em>へ、<em>第2ビット</em>は<em>第2ビット</em>へ、という具合にです。</p> + +<p>この演算子は各ビットの組み合わせに適用され、結果はビット単位に構築されます。</p> + +<p><code>NOT</code> 演算の真理値表は次のようになります。</p> + +<table class="standard-table"> + <thead> + <tr> + <th class="header" scope="col">a</th> + <th class="header" scope="col">NOT a</th> + </tr> + </thead> + <tbody> + <tr> + <td>0</td> + <td>1</td> + </tr> + <tr> + <td>1</td> + <td>0</td> + </tr> + </tbody> +</table> + +<pre class="brush: js notranslate"> 9 (10進数) = 00000000000000000000000000001001 (2進数) + -------------------------------- +~9 (10進数) = 11111111111111111111111111110110 (2進数) = -10 (10進数) +</pre> + +<p>ある数 <code>x</code> のビット否定 は <code>-(x + 1)</code> になります。例えば、<code>~-5</code> は <code>4</code> になります。</p> + +<p>数値に32ビット表現を使用するため <code>~-1</code> および <code>~4294967295</code> (2<sup>32</sup>-1) はいずれも <code>0</code> になることに注意してください。</p> + +<h2 id="例">例</h2> + +<h3 id="ビット否定の使用">ビット否定の使用</h3> + +<pre class="brush: js notranslate">~0; // -1 +~-1; // 0 +~1; // -2 +</pre> + +<h2 id="仕様">仕様</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">仕様書</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-unary-operators', 'Unary NOT expression')}}</td> + </tr> + </tbody> +</table> + +<h2 id="ブラウザーの互換性">ブラウザーの互換性</h2> + + + +<p>{{Compat("javascript.operators.bitwise_not")}}</p> + +<h2 id="関連情報">関連情報</h2> + +<ul> + <li><a href="/ja/docs/Web/JavaScript/Guide/Expressions_and_Operators#Bitwise_operators">ビット演算子ガイド</a></li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/bitwise_or/index.html b/files/ja/web/javascript/reference/operators/bitwise_or/index.html new file mode 100644 index 0000000000..f6317e19bc --- /dev/null +++ b/files/ja/web/javascript/reference/operators/bitwise_or/index.html @@ -0,0 +1,116 @@ +--- +title: ビット論理和 (|) +slug: Web/JavaScript/Reference/Operators/Bitwise_OR +tags: + - Bitwise operator + - JavaScript + - Language feature + - Operator + - Reference + - 演算子 + - 言語機能 +translation_of: Web/JavaScript/Reference/Operators/Bitwise_OR +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>ビット論理和演算子 (<code>|</code>) は、両方のオペランドの対応するビットのどちらか一方が <code>1</code> である位置のビットで <code>1</code> を返します。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-bitwise-or.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"><code><var>a</var> | <var>b</var></code> +</pre> + +<h2 id="Description" name="Description">解説</h2> + +<p>オペランドは32ビットの整数値に変換され、ビット (ゼロまたは1) の並びによって表現されます。32ビットを超える数値は最上位のビットが破棄されます。例えば、次の32ビットを超える整数は32ビット整数に変換されます。</p> + +<pre class="brush: js notranslate">変換前: 11100110111110100000000000000110000000000001 +変換後: 10100000000000000110000000000001</pre> + +<p>第1オペランドの各ビットは、第2オペランドの対応するビットと組み合わせになります。<em>第1ビット</em>は<em>第1ビット</em>へ、<em>第2ビット</em>は<em>第2ビット</em>へ、という具合にです。</p> + +<p>この演算子は各ビットの組み合わせに適用され、結果はビット単位で構築されます。</p> + +<p>OR 演算の真理値表は次のようになります。</p> + +<table class="standard-table"> + <thead> + <tr> + <th class="header" scope="col">a</th> + <th class="header" scope="col">b</th> + <th class="header" scope="col">a OR b</th> + </tr> + </thead> + <tbody> + <tr> + <td>0</td> + <td>0</td> + <td>0</td> + </tr> + <tr> + <td>0</td> + <td>1</td> + <td>1</td> + </tr> + <tr> + <td>1</td> + <td>0</td> + <td>1</td> + </tr> + <tr> + <td>1</td> + <td>1</td> + <td>1</td> + </tr> + </tbody> +</table> + +<pre class="brush: js notranslate">. 9 (10進数) = 00000000000000000000000000001001 (2進数) + 14 (10進数) = 00000000000000000000000000001110 (2進数) + -------------------------------- +14 | 9 (10進数) = 00000000000000000000000000001111 (2進数) = 15 (10進数) +</pre> + +<p>ある数 <code><var>x</var></code> と <code>0</code> のビット論理和は <code><var>x</var></code> になります。</p> + +<h2 id="Examples" name="Examples">例</h2> + +<h3 id="Using_bitwise_OR" name="Using_bitwise_OR">ビット論理和の使用</h3> + +<pre class="brush: js notranslate">// 9 (00000000000000000000000000001001) +// 14 (00000000000000000000000000001110) + +14 | 9; +// 15 (00000000000000000000000000001111)</pre> + +<h2 id="Specifications" name="Specifications">仕様</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">仕様書</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#prod-BitwiseORExpression', 'Bitwise OR expression')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">ブラウザーの互換性</h2> + +<div class="hidden">このページの互換性一覧表は構造化データから生成されています。データに協力していただけるのであれば、 <a class="external" href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> をチェックアウトしてプルリクエストを送信してください。</div> + +<p>{{Compat("javascript.operators.bitwise_or")}}</p> + +<h2 id="See_also" name="See_also">関連情報</h2> + +<ul> + <li><a href="/docs/Web/JavaScript/Guide/Expressions_and_Operators#Bitwise">ビット演算子ガイド</a></li> + <li><a href="/docs/Web/JavaScript/Reference/Operators/Bitwise_OR_assignment">ビット論理和代入演算子</a></li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/bitwise_or_assignment/index.html b/files/ja/web/javascript/reference/operators/bitwise_or_assignment/index.html new file mode 100644 index 0000000000..384c541b62 --- /dev/null +++ b/files/ja/web/javascript/reference/operators/bitwise_or_assignment/index.html @@ -0,0 +1,66 @@ +--- +title: ビット論理和代入 (|=) +slug: Web/JavaScript/Reference/Operators/Bitwise_OR_assignment +tags: + - Assignment operator + - Deprecated + - JavaScript + - Language feature + - Operator + - Reference + - 代入演算子 + - 演算子 +translation_of: Web/JavaScript/Reference/Operators/Bitwise_OR_assignment +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>ビット論理和代入演算子 (<code>|=</code>) は、両方のオペランドの二進表現を使用し、これらにビット単位の OR 演算を行って、結果を変数に代入します。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-bitwise-or-assignment.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"><strong>演算子:</strong> x |= y +<strong>意味:</strong> x = x | y</pre> + +<h2 id="Examples" name="Examples">例</h2> + +<h3 id="Using_bitwise_OR_assignment" name="Using_bitwise_OR_assignment">ビット論理和代入の使用</h3> + +<pre class="brush: js notranslate">let a = 5; +a |= 2; // 7 +// 5: 00000000000000000000000000000101 +// 2: 00000000000000000000000000000010 +// ----------------------------------- +// 7: 00000000000000000000000000000111</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-assignment-operators', 'Assignment operators')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">ブラウザーの互換性</h2> + +<div class="hidden">このページの互換性一覧表は構造化データから生成されています。データに協力していただけるのであれば、 <a class="external" href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> をチェックアウトしてプルリクエストを送信してください。</div> + +<p>{{Compat("javascript.operators.bitwise_or_assignment")}}</p> + +<h2 id="See_also" name="See_also">関連情報</h2> + +<ul> + <li><a href="/ja/docs/Web/JavaScript/Guide/Expressions_and_Operators#Assignment">ビット演算子ガイド</a></li> + <li><a href="/ja/docs/Web/JavaScript/Reference/Operators/Bitwise_OR">ビット論理和演算子</a></li> + <li><a href="/ja/docs/Web/JavaScript/Reference/Operators/Logical_OR_assignment">論理和代入 (<code>||=</code>)</a></li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/bitwise_xor/index.html b/files/ja/web/javascript/reference/operators/bitwise_xor/index.html new file mode 100644 index 0000000000..97ec807b49 --- /dev/null +++ b/files/ja/web/javascript/reference/operators/bitwise_xor/index.html @@ -0,0 +1,116 @@ +--- +title: ビット排他的論理和 (^) +slug: Web/JavaScript/Reference/Operators/Bitwise_XOR +tags: + - Bitwise operator + - JavaScript + - Language feature + - Operator + - Reference + - 演算子 + - 言語機能 +translation_of: Web/JavaScript/Reference/Operators/Bitwise_XOR +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>ビット排他的論理和演算子 (<code>^</code>) は、両方のオペランドの対応するビットの一方だけが <code>1</code> である位置のビットで <code>1</code> を返します。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-bitwise-xor.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"><code><var>a</var> ^ <var>b</var></code> +</pre> + +<h2 id="Description" name="Description">解説</h2> + +<p>オペランドは32ビットの整数値に変換され、ビット (ゼロまたは1) の並びによって表現されます。32ビットを超える数値は最上位のビットが破棄されます。例えば、次の32ビットを超える整数は32ビット整数に変換されます。</p> + +<pre class="brush: js notranslate">変換前: 11100110111110100000000000000110000000000001 +変換後: 10100000000000000110000000000001</pre> + +<p>第1オペランドの各ビットは、第2オペランドの対応するビットと組み合わせになります。<em>第1ビット</em>は<em>第1ビット</em>へ、<em>第2ビット</em>は<em>第2ビット</em>へ、という具合にです。</p> + +<p>この演算子は各ビットの組み合わせに適用され、結果はビット単位に構築されます。</p> + +<p>XOR 演算の真理値表は次のようになります。</p> + +<table class="standard-table"> + <thead> + <tr> + <th class="header" scope="col">a</th> + <th class="header" scope="col">b</th> + <th class="header" scope="col">a XOR b</th> + </tr> + </thead> + <tbody> + <tr> + <td>0</td> + <td>0</td> + <td>0</td> + </tr> + <tr> + <td>0</td> + <td>1</td> + <td>1</td> + </tr> + <tr> + <td>1</td> + <td>0</td> + <td>1</td> + </tr> + <tr> + <td>1</td> + <td>1</td> + <td>0</td> + </tr> + </tbody> +</table> + +<pre class="brush: js notranslate">. 9 (10進数) = 00000000000000000000000000001001 (2進数) + 14 (10進数) = 00000000000000000000000000001110 (2進数) + -------------------------------- +14 ^ 9 (10進数) = 00000000000000000000000000000111 (2進数) = 7 (10進数) +</pre> + +<p>ある数 <code><var>x</var></code> と <code>0</code> のビット排他的論理和は <code><var>x</var></code> になります。</p> + +<h2 id="Examples" name="Examples">例</h2> + +<h3 id="Using_bitwise_XOR" name="Using_bitwise_XOR">ビット排他的論理和の使用</h3> + +<pre class="brush: js notranslate">// 9 (00000000000000000000000000001001) +// 14 (00000000000000000000000000001110) + +14 ^ 9; +// 7 (00000000000000000000000000000111)</pre> + +<h2 id="Specifications" name="Specifications">仕様</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">仕様書</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#prod-BitwiseXORExpression', 'Bitwise XOR expression')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">ブラウザーの互換性</h2> + +<div class="hidden">このページの互換性一覧表は構造化データから生成されています。データに協力していただけるのであれば、 <a class="external" href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> をチェックアウトしてプルリクエストを送信してください。</div> + +<p>{{Compat("javascript.operators.bitwise_xor")}}</p> + +<h2 id="See_also" name="See_also">関連情報</h2> + +<ul> + <li><a href="/ja/docs/Web/JavaScript/Guide/Expressions_and_Operators#Bitwise">ビット演算子ガイド</a></li> + <li><a href="/ja/docs/Web/JavaScript/Reference/Operators/Bitwise_XOR_assignment">ビット排他的論理和代入演算子</a></li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/bitwise_xor_assignment/index.html b/files/ja/web/javascript/reference/operators/bitwise_xor_assignment/index.html new file mode 100644 index 0000000000..25ffd6de5c --- /dev/null +++ b/files/ja/web/javascript/reference/operators/bitwise_xor_assignment/index.html @@ -0,0 +1,71 @@ +--- +title: ビット排他的論理和代入 (^=) +slug: Web/JavaScript/Reference/Operators/Bitwise_XOR_assignment +tags: + - Assignment operator + - JavaScript + - Language feature + - Operator + - Reference +translation_of: Web/JavaScript/Reference/Operators/Bitwise_XOR_assignment +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>ビット排他的論理和代入演算子 (<code>^=</code>) は、両方のオペランドのバイナリ表現を使用し、それらに対してビット単位の XOR 演算を実行し、結果を変数に代入します。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-bitwise-xor-assignment.html")}}</div> + +<div></div> + + + +<h2 id="構文">構文</h2> + +<pre class="syntaxbox notranslate"><strong>Operator:</strong> x ^= y +<strong>Meaning:</strong> x = x ^ y</pre> + +<h2 id="例">例</h2> + +<h3 id="ビット排他的論理和代入の使用">ビット排他的論理和代入の使用</h3> + +<pre class="brush: js notranslate">let a = 5; // 00000000000000000000000000000101 +a ^= 3; // 00000000000000000000000000000011 + +console.log(a); // 00000000000000000000000000000110 +// 6 + +let b = 5; // 00000000000000000000000000000101 +b ^= 0; // 00000000000000000000000000000000 + +console.log(b); // 00000000000000000000000000000101 +// 5 + + + +</pre> + +<h2 id="仕様">仕様</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">仕様書</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-assignment-operators', 'Assignment operators')}}</td> + </tr> + </tbody> +</table> + +<h2 id="ブラウザーの互換性">ブラウザーの互換性</h2> + + + +<p>{{Compat("javascript.operators.bitwise_xor_assignment")}}</p> + +<h2 id="関連項目">関連項目</h2> + +<ul> + <li><a href="/docs/Web/JavaScript/Guide/Expressions_and_Operators#Assignment_operators">代入演算子ガイド</a></li> + <li><a href="/docs/Web/JavaScript/Reference/Operators/Bitwise_XOR">ビット排他的論理和演算子</a></li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/class/index.html b/files/ja/web/javascript/reference/operators/class/index.html new file mode 100644 index 0000000000..289bba4253 --- /dev/null +++ b/files/ja/web/javascript/reference/operators/class/index.html @@ -0,0 +1,116 @@ +--- +title: クラス式 +slug: Web/JavaScript/Reference/Operators/class +tags: + - Class + - Classes + - ECMAScript6 + - Expression + - JavaScript + - Operator + - Reference +translation_of: Web/JavaScript/Reference/Operators/class +--- +<div>{{jsSidebar("Operators")}}</div> + +<p><span class="seoSummary"><strong>クラス式</strong>は、 ECMAScript 2015 でクラスを定義する方法の 1 つです。{{jsxref("Operators/function", "関数式", "", "true")}}と同じように、クラス式は名前を付けることも付けないこともできます。名前を付ける場合、クラス名はクラス内部のみのローカルです。</span></p> + +<p>JavaScript のクラスはプロトタイプベースの継承が使われます。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-classexpression.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">const <var>MyClass</var> = class [<var>className</var>] [extends <var>otherClassName</var>] { + // クラス本体 +};</pre> + +<h2 id="Description" name="Description">説明</h2> + +<p>クラス式の構文は、{{jsxref("Statements/class", "クラス宣言 (文)", "", "true")}} と似ています。 <code>class</code> 文では、 <code>class</code> 式の本体が{{jsxref("Strict_mode", "厳格モード", "", 1)}}で実行されます。</p> + +<p>しかし、クラス式と{{jsxref("Statements/class", "クラス文", "", "true")}}はいくつかの相違点があります。</p> + +<ul> + <li>クラス式ではクラス名 ("<ruby>束縛識別子<rp> (</rp><rt>binding identifier</rt><rp>) </rp></ruby>") を省略できますが、{{jsxref("Statements/class", "クラス文", "", "true")}}では省略できません。</li> + <li>クラス式は {{jsxref("Global_Objects/SyntaxError", "SyntaxError")}} <strong>を発生させずに</strong>クラスを再宣言することができます。これは{{jsxref("Statements/class", "クラス文", "", "true")}}の場合はできません。</li> +</ul> + +<p><code>constructor</code> メソッドは省略可能です。クラス式で生成されたクラスは、常に {{jsxref("Operators/typeof", "typeof")}} が "<code>function</code>" の値を返します。</p> + +<pre class="brush: js notranslate">'use strict'; +let Foo = class {}; // コンストラクタープロパティは省略可能 +Foo = class {}; // 再宣言が可能 + +typeof Foo; // "function" を返す +typeof class {}; // "function" を返す + +Foo instanceof Object; // true +Foo instanceof Function; // true +class Foo {} // SyntaxError が発生 (クラス<em>宣言</em>は再宣言ができない) +</pre> + +<h2 id="Examples" name="Examples">例</h2> + +<h3 id="A_simple_class_expression" name="A_simple_class_expression">簡単なクラス式</h3> + +<p>以下は、名前のない簡単なクラス式です。変数 <code>Foo</code> を使って参照できます。</p> + +<pre class="brush: js notranslate">const Foo = class { + constructor() {} + bar() { + return 'Hello World!'; + } +}; + +const instance = new Foo(); +instance.bar(); // "Hello World!" +Foo.name; // "Foo" +</pre> + +<h3 id="Named_class_expressions" name="Named_class_expressions">名前付きクラス式</h3> + +<p>クラス内部で現在のクラスを参照したい場合は、<em>名前付きクラス式</em>を作成してください。この名前は、そのクラス式自身のスコープ内だけで見ることができます。</p> + +<pre class="brush: js notranslate">const Foo = class NamedFoo { + constructor() {} + whoIsThere() { + return NamedFoo.name; + } +} +const bar = new Foo(); +bar.whoIsThere(); // "NamedFoo" +NamedFoo.name; // ReferenceError: NamedFoo is not defined +Foo.name; // "NamedFoo" +</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-class-definitions', 'Class definitions')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">ブラウザーの互換性</h2> + +<div class="hidden">このページの互換性一覧表は構造化データから生成されています。データに協力していただけるのであれば、 <a class="external" href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> をチェックアウトしてプルリクエストを送信してください。</div> + +<p>{{Compat("javascript.operators.class")}}</p> + +<h2 id="See_also" name="See_also">関連情報</h2> + +<ul> + <li>{{jsxref("Operators/function", "関数式", "", "true")}}</li> + <li>{{jsxref("Statements/class", "クラス宣言", "", "true")}}</li> + <li>{{jsxref("Classes", "クラス", "", "true")}}</li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/comma_operator/index.html b/files/ja/web/javascript/reference/operators/comma_operator/index.html new file mode 100644 index 0000000000..a8e460a4d3 --- /dev/null +++ b/files/ja/web/javascript/reference/operators/comma_operator/index.html @@ -0,0 +1,94 @@ +--- +title: 'カンマ演算子 (,)' +slug: Web/JavaScript/Reference/Operators/Comma_Operator +tags: + - Comma + - Compound + - Expression + - JavaScript + - Language feature + - Operator + - Reference +translation_of: Web/JavaScript/Reference/Operators/Comma_Operator +--- +<div>{{jsSidebar("Operators")}}</div> + +<p><strong>カンマ演算子</strong> (<strong><code>,</code></strong>) は、それぞれの演算対象を(左から右に)評価し、最後のオペランドの値を返します。これにより、複数の式が評価される複合式を作成することができ、複合式の最終値はそのメンバ式の一番右端の値となります。これは、<code><a href="/docs/Web/JavaScript/Reference/Statements/for">for</a></code> ループに複数のパラメーターを提供する場合によく使用されます。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-commaoperators.html")}}</div> + + + +<h2 id="Syntax" name="Syntax">構文</h2> + +<pre class="syntaxbox notranslate"><em>expr1</em>, <em>expr2, expr3...</em></pre> + +<h2 id="Parameters" name="Parameters">パラメーター</h2> + +<dl> + <dt><code>expr1</code>, <code>expr2</code>, <code>expr3</code>...</dt> + <dd>1つ以上の式で、最後の式が複合式の値として返されます。</dd> +</dl> + +<h2 id="Description" name="Description">説明</h2> + +<p>単一の式でなければならない位置で複数の式を記述したい場合に、カンマ演算子を使うことができます。この演算子が最も良く使われるのは、<code>for</code> ループで複数のパラメーターを与えたい時です。</p> + +<p>カンマ演算子は、配列、オブジェクト、関数の引数やパラメーターの内部にあるカンマとは大きく異なります。</p> + +<h2 id="Examples" name="Examples">例</h2> + +<p>例えば次のコードでは、<code>a</code> が、1 辺 10 要素からなる 2 次元配列内の要素を一度に 2 つ 変化させる為に、変数宣言部分でカンマ演算子を用いています。</p> + +<p>このコードは、配列における対角線の要素の値を出力するものです。</p> + +<pre class="brush:js;highlight:[1] notranslate">for (var i = 0, j = 9; i <= 9; i++, j--) + document.writeln("a[" + i + "][" + j + "] = " + a[i][j]);</pre> + +<p>(<code>var</code> 文などで)代入を行う際にカンマを使うと、カンマ演算子が通常どおりに働いていないかのように見える場合があります(カンマ演算子が式の中にないため)。以下の例で <code>a</code> には <code>b = 3</code> の値(すなわち 3 )が設定されますが、さらに <code>c = 4</code> が評価されて、その結果 (4) がコンソールに返ります。これは<a href="/ja/docs/Web/JavaScript/Reference/Operators/Operator_Precedence">演算子の優先順位と結合性</a>のためです。</p> + +<pre class="brush: js notranslate">var a, b, c; + +a = b = 3, c = 4; // コンソールに 4 が返る +console.log(a); // 3 (もっとも左) + +var x, y, z; + +x = (y = 5, z = 6); // コンソールに 6 が返る +console.log(x); // 6 (もっとも右) +</pre> + +<h3 id="Processing_and_then_returning" name="Processing_and_then_returning">処理と戻り値</h3> + +<p>カンマ演算子が行うことのもうひとつの例が、値を返す前の処理です。前述のとおり最後の要素のみ返しますが、その他すべての要素も評価します。よって、以下のようなことができます:</p> + +<pre class="brush: js notranslate">function myFunc () { + var x = 0; + + return (x += 1, x); // 戻り値は ++x と同じ +}</pre> + +<h2 id="Specifications" name="Specifications">仕様</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">仕様書</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-comma-operator', 'Comma operator')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">ブラウザー実装状況</h2> + + + +<p>{{Compat("javascript.operators.comma")}}</p> + +<h2 id="See_also" name="See_also">関連情報</h2> + +<ul> + <li><a href="/ja/docs/Web/JavaScript/Reference/Statements/for">for ループ</a></li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/comparison_operators/index.html b/files/ja/web/javascript/reference/operators/comparison_operators/index.html new file mode 100644 index 0000000000..701e2081f3 --- /dev/null +++ b/files/ja/web/javascript/reference/operators/comparison_operators/index.html @@ -0,0 +1,231 @@ +--- +title: 比較演算子 +slug: Web/JavaScript/Reference/Operators/Comparison_Operators +tags: + - JavaScript + - Operator + - Reference + - 演算子 +translation_of: Web/JavaScript/Reference/Operators +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>JavaScript には、厳密な比較と型変換の比較の両方があります。厳密な比較 (例: <code>===</code>) は、オペランドが同じ型で、内容も一致している場合にのみ真になります。もっとよく使用される抽象的な比較 (例: <code>==</code>) は、比較する前にオペランドを同じ型に変換します。抽象的な関係比較 (例: <code><=</code>) では、比較前にまずオペランドがプリミティブ型に変換され、それから同じ型に変換されます。</p> + +<p>文字列は Unicode 値を使用した標準的な辞書順に基づいて比較されます。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-equality.html")}}</div> + +<div> +<div>{{EmbedInteractiveExample("pages/js/expressions-strict-equality.html")}}</div> +</div> + +<div></div> + +<p class="hidden">このデモのソースファイルは GitHub リポジトリに格納されています。デモプロジェクトに協力したい場合は、 <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> をクローンしてプルリクエストを送信してください。</p> + +<p>比較の機能は以下のとおりです。</p> + +<ul> + <li>2 つの文字列が厳密に等しくなるのは、字の順序が等しく、長さが等しく、対応する位置の文字が等しいときです。</li> + <li>2 つの数字が厳密に等しくなるのは、数値的に等しいとき (数字の値が等しいとき) です。<a href="/ja/docs/Web/JavaScript/Reference/Global_Objects/NaN" title="NaN">NaN</a> は、どんなものとも (Nan とさえも) 等しくなりません。プラスゼロとマイナスゼロは互いと等しくなります。</li> + <li>2 つの論理オペランドが厳密に等しくなるのは、どちらも <code>true</code> か、どちらも <code>false</code> のときです。</li> + <li>2 つの異なるオブジェクトは、厳密な比較でも抽象的な比較でも等しくなりません。</li> + <li>オブジェクト比較が等しくなるのは、オペランドが同じオブジェクトを参照しているときだけです。</li> + <li>Null と Undefined 型は、自分自身と厳密に等しく、また互いに抽象的に等しくなります。</li> +</ul> + +<h2 id="Equality_operators" name="Equality_operators">等価演算子</h2> + +<h3 id="Equality" name="Equality">等価 (==)</h3> + +<p>等価演算子は、2 つのオペランドが<strong>同じ型でないならば</strong>オペランドを変換して、それから厳密な比較を行います。<strong>両方のオペランドがオブジェクトならば</strong>、 JavaScript は内部参照を比較するので、オペランドがメモリ内の同じオブジェクトを参照するときに等しくなります。</p> + +<h4 id="Syntax" name="Syntax">構文</h4> + +<pre class="syntaxbox notranslate">x == y +</pre> + +<h4 id="Examples" name="Examples">例</h4> + +<pre class="brush: js notranslate">1 == 1 // true +'1' == 1 // true +1 == '1' // true +0 == false // true +0 == null // false +var object1 = {'key': 'value'}, object2 = {'key': 'value'}; +object1 == object2 // false +0 == undefined // false +null == undefined // true +</pre> + +<h3 id="Inequality" name="Inequality">不等価 (!=)</h3> + +<p>不等価演算子は、オペランド同士が等しくないならば真を返します。2 つのオペランドが<strong>同じ型でないならば</strong>、JavaScript は適切な型にオペランドを変換して比較しようとします。<strong>両方のオペランドがオブジェクトならば</strong>、JavaScript は内部参照を比較するので、オペランドがメモリ内の異なるオブジェクトを参照するときには等しくなりません。</p> + +<h4 id="Syntax_2" name="Syntax_2">構文</h4> + +<pre class="syntaxbox notranslate">x != y</pre> + +<h4 id="Examples_2" name="Examples_2">例</h4> + +<pre class="brush: js notranslate">1 != 2 // true +1 != '1' // false +1 != "1" // false +1 != true // false +0 != false // false +</pre> + +<h3 id="Identity" name="Identity">一致 / 厳密等価 (===)</h3> + +<p>厳密等価演算子は、<strong>型変換なしで</strong>オペランド同士が (上に示した通り) 厳密に等しければ真を返します。</p> + +<h4 id="Syntax_3" name="Syntax_3">構文</h4> + +<pre class="syntaxbox notranslate">x === y</pre> + +<h4 id="Examples_3" name="Examples_3">例</h4> + +<pre class="brush: js notranslate">3 === 3 // true +3 === '3' // false +var object1 = {'key': 'value'}, object2 = {'key': 'value'}; +object1 === object2 //false</pre> + +<h3 id="Nonidentity" name="Nonidentity">不一致 / 厳密不等価 (!==)</h3> + +<p>厳密不等価演算子は、<strong>オペランド同士が等しくないか、型が等しくない、あるいはその両方</strong>ならば真を返します。</p> + +<h4 id="Syntax_4" name="Syntax_4">構文</h4> + +<pre class="syntaxbox notranslate">x !== y</pre> + +<h4 id="Examples_4" name="Examples_4">例</h4> + +<pre class="brush: js notranslate">3 !== '3' // true +4 !== 3 // true +</pre> + +<h2 id="Relational_operators" name="Relational_operators">関係演算子</h2> + +<p>これらの演算子のそれぞれは、比較が行われる前に、そのオペランドをプリミティブに{{Glossary("Type_coercion", "型強制")}}します。両方とも文字列として終わる場合は、辞書順で比較され、そうでない場合は数値に変換されて比較されます。 <code>NaN</code> との比較は常に <code>false</code> を生み出します。</p> + +<h3 id="Greater_than_operator" name="Greater_than_operator">大なり演算子 (>)</h3> + +<p>大なり演算子は、左オペランドが右オペランドより大きければ、真を返します。</p> + +<h4 id="Syntax_5" name="Syntax_5">構文</h4> + +<pre class="syntaxbox notranslate">x > y</pre> + +<h4 id="Examples_5" name="Examples_5">例</h4> + +<pre class="brush: js notranslate">4 > 3 // true +</pre> + +<h3 id="Greater_than_or_equal_operator" name="Greater_than_or_equal_operator">大なりイコール演算子 (>=)</h3> + +<p>大なりイコール演算子は、左オペランドが右オペランド以上ならば、真を返します。</p> + +<h4 id="Syntax_6" name="Syntax_6">構文</h4> + +<pre class="syntaxbox notranslate"> x >= y</pre> + +<h4 id="Examples_6" name="Examples_6">例</h4> + +<pre class="brush: js notranslate">4 >= 3 // true +3 >= 3 // true +</pre> + +<h3 id="Less_than_operator" name="Less_than_operator">小なり演算子 (<)</h3> + +<p>小なり演算子は、左オペランドが右オペランドより小さければ、真を返します。</p> + +<h4 id="Syntax_7" name="Syntax_7">構文</h4> + +<pre class="syntaxbox notranslate"> x < y</pre> + +<h4 id="Examples_7" name="Examples_7">例</h4> + +<pre class="brush: js notranslate">3 < 4 // true +</pre> + +<h3 id="Less_than_or_equal_operator" name="Less_than_or_equal_operator">小なりイコール演算子 (<=)</h3> + +<p>小なりイコール演算子は、左オペランドが右オペランド以下ならば、真を返します。</p> + +<h4 id="Syntax_8" name="Syntax_8">構文</h4> + +<pre class="syntaxbox notranslate"> x <= y</pre> + +<h4 id="Examples_8" name="Examples_8">例</h4> + +<pre class="brush: js notranslate">3 <= 4 // true +3 <= 3 // true +</pre> + +<h2 id="Using_the_equality_operators" name="Using_the_equality_operators">等価演算子の使用</h2> + +<p>標準等価演算子 (<code>==</code> と <code>!=</code>) は 2 つのオペランドの比較に<a href="http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3">抽象的等価比較アルゴリズム</a>を使用します。オペランドの型が異なる場合は、比較を行う前にそれらを同じ型に変換しようとします。例えば <code>5 == '5'</code> という式では、比較を行う前に右オペランドの文字列を数値に変換します。</p> + +<p>厳密等価演算子 (<code>===</code> と <code>!==</code>) は<a href="http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.6">厳密等価比較アルゴリズム</a>を使用して、オペランドの型が同一かどうかに関する比較も行います。オペランドの型が異なれば、例えば <code>5</code> と <code>'5'</code> の比較では、同一性比較 <code>5 !== '5'</code> は <code>true</code> と評価され、 <code>5 === '5'</code> のチェックは <code>false</code> 評価されます。</p> + +<p>厳密等価演算子を使うのは、オペランドが特定の型の特定の値でなければならない場合、言い換えればオペランドの正確な型が重要な場合です。それ以外では、2 つのオペランドが同じ型でなくても比較が可能になる、標準的な等価演算子を使えます。</p> + +<p>比較に型の変換が関わるとき (つまり厳密でない比較のとき)、 JavaScript は以下のように {{jsxref("String")}}, {{jsxref("Number")}}, {{jsxref("Boolean")}}, {{jsxref("Object")}} 型のオペランドを変換します。</p> + +<ul> + <li>数値と文字列を比較するとき、文字列は数値に変換されます。 JavaScript は文字列の数値リテラルを <code>Number</code> 型の値に変換しようとします。まず、文字列の数値リテラルから数学的な値を引き出します。次に、その値を最も近い <code>Number</code> 型に丸めます。</li> + <li>もしオペランドの片方が <code>Boolean</code> ならば、その Boolean オペランドが <code>true</code> の場合 1 に、<code>false</code> の場合は +0 に変換されます。</li> + <li>オブジェクトを数値または文字列と比較すると、 JavaScript はそのオブジェクトの既定値を返そうとします。演算子は、オブジェクトの <code>valueOf</code> や <code>toString</code> といったメソッドを用いて、プリミティブな値、 <code>String</code> か <code>Number</code> の値に変換しようとします。変換に失敗したら、ランタイムエラーが発生します。</li> + <li>オブジェクトがプリミティブ値に変換されるのは、比較対象がプリミティブ値であるときだけです。両方のオペランドがオブジェクトなら、オブジェクトとして比較され、両方が同じオブジェクトを参照するときだけ真となります。</li> +</ul> + +<div class="note"><strong>メモ:</strong> String オブジェクトはオブジェクト型であり、文字列型ではありません! String オブジェクトはほとんど使わないので、次の結果に驚くかもしれません。</div> + +<pre class="brush:js notranslate">// 両方のオペランドが文字列型 (すなわちプリミティブな文字列) なので、true +'foo' === 'foo' + +var a = new String('foo'); +var b = new String('foo'); + +// a と b はオブジェクト型で、異なるオブジェクトを参照しているので、false +a == b + +// a と b はオブジェクト型で、異なるオブジェクトを参照しているので、false +a === b + +// a と 'foo' は異なる型で、比較前にオブジェクト (a) は +// 文字列 'foo' に変換されるので、真 +a == 'foo'</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-equality-operators', 'Equality Operators')}}</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-relational-operators', 'Relational Operators')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">ブラウザーの互換性</h2> + +<div class="hidden">このページの互換性一覧表は構造化データから生成されています。データに協力していただけるのであれば、 <a class="external" href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> をチェックアウトしてプルリクエストを送信してください。</div> + +<p>{{Compat("javascript.operators.comparison")}}</p> + +<h2 id="See_also" name="See_also">関連情報</h2> + +<ul> + <li>{{jsxref("Object.is()")}}</li> + <li>{{jsxref("Math.sign()")}}</li> + <li><a href="/ja/docs/Web/JavaScript/Equality_comparisons_and_sameness">等価性の比較とその使いどころ</a></li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/conditional_operator/index.html b/files/ja/web/javascript/reference/operators/conditional_operator/index.html new file mode 100644 index 0000000000..19afa5445a --- /dev/null +++ b/files/ja/web/javascript/reference/operators/conditional_operator/index.html @@ -0,0 +1,115 @@ +--- +title: 条件 (三項) 演算子 +slug: Web/JavaScript/Reference/Operators/Conditional_Operator +tags: + - Conditional + - JS + - JavaScript + - Operator + - Reference + - ternary + - 三項 + - 条件 + - 演算子 +translation_of: Web/JavaScript/Reference/Operators/Conditional_Operator +--- +<div>{{jsSidebar("Operators")}}</div> + +<p><span class="seoSummary"><strong>条件 (三項) 演算子</strong>は JavaScript では唯一の、3 つのオペランドをとる演算子です。条件に続いて疑問符 (<code>?</code>)、そして条件が{{Glossary("truthy", "真値")}}であった場合に実行する式、コロン (<code>:</code>) が続き、条件が{{Glossary("falsy")}}であった場合に実行する式が最後に来ます。</span>この演算子は、 <a href="/ja/docs/Web/JavaScript/Reference/Statements/if...else"><code>if</code></a> 文のショートカットとしてよく用いられます。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-conditionaloperators.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>condition</var> ? <var>exprIfTrue</var> : <var>exprIfFalse</var></pre> + +<h3 id="Parameters" name="Parameters">引数</h3> + +<dl> + <dt><code><var>condition</var></code></dt> + <dd>値が条件として使用される式です。</dd> + <dt><code><var>exprIfTrue</var></code></dt> + <dd><code><var>condition</var></code> が {{Glossary("truthy")}} の値 (<code>true</code> と等しいか、 <code>true</code> に変換できる値) と評価された場合に評価される式です。</dd> + <dt><code><var>exprIfFalse</var></code></dt> + <dd><code><var>condition</var></code> が {{Glossary("falsy")}} の値 (<code>false</code> と等しいか、 <code>false</code> に変換できる値) と評価された場合に評価される式です。</dd> +</dl> + +<h2 id="Description" name="Description">解説</h2> + +<p><code>false</code> についていえば、 falsy になる可能性がある式は <code>null</code>, <code>NaN</code>, <code>0</code>, 空文字列 (<code>""</code>), <code>undefined</code> です。 <code><var>condition</var></code> がこのうちの何れかであれば、条件演算子の結果は <code>exprIfFalse</code> の式を実行した結果になります。</p> + +<h2 id="Examples" name="Examples">例</h2> + +<h3 id="A_simple_example" name="A_simple_example">単純な例</h3> + +<pre class="brush: js notranslate">var age = 26; +var beverage = (age >= 21) ? "ビール" : "ジュース"; +console.log(beverage); // "ビール" +</pre> + +<h3 id="Handling_null_values" name="Handling_null_values">null 値の扱い</h3> + +<p>よくある使い方の一つに、 <code>null</code> になる可能性がある値を扱うというものがあります。</p> + +<pre class="brush: js notranslate">let greeting = person => { + let name = person ? person.name : `お客さん` + return `やあ、${name}` +} + +console.log(greeting({name: `アリス`})); // "やあ、アリス" +console.log(greeting(null)); // "やあ、お客さん" +</pre> + +<h3 id="Conditional_chains" name="Conditional_chains">条件の連鎖</h3> + +<p>三項演算子は右結合で、すなわち以下のような方法で <code>if … else if … else if … else</code> の連鎖と同様に「連鎖」させることができます。</p> + +<pre class="brush: js notranslate">function example(…) { + return condition1 ? value1 + : condition2 ? value2 + : condition3 ? value3 + : value4; +} + +// 以下のものと同等です。 + +function example(…) { + if (condition1) { return value1; } + else if (condition2) { return value2; } + else if (condition3) { return value3; } + else { return value4; } +} +</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-conditional-operator', 'Conditional Operator')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">ブラウザーの互換性</h2> + +<div class="hidden">このページの互換性一覧表は構造化データから生成されています。データに協力していただけるのであれば、 <a class="external" href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> をチェックアウトしてプルリクエストを送信してください。</div> + +<p>{{Compat("javascript.operators.conditional")}}</p> + +<h2 id="See_also" name="See_also">関連情報</h2> + +<ul> + <li><a href="/ja/docs/Web/JavaScript/Reference/Statements/if...else">if 文</a></li> + <li><a href="/ja/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator">Null 合体演算子</a></li> + <li><a href="/ja/docs/Web/JavaScript/Reference/Operators/Optional_chaining">オプション連鎖</a></li> + <li><a href="/ja/docs/Learn/JavaScript/Building_blocks/conditionals">コードでの意思決定 — 条件文</a></li> + <li><a href="/ja/docs/Web/JavaScript/Guide/Expressions_and_Operators">式と演算子</a></li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/decrement/index.html b/files/ja/web/javascript/reference/operators/decrement/index.html new file mode 100644 index 0000000000..b22545059c --- /dev/null +++ b/files/ja/web/javascript/reference/operators/decrement/index.html @@ -0,0 +1,83 @@ +--- +title: デクリメント (--) +slug: Web/JavaScript/Reference/Operators/Decrement +tags: + - Decrement + - JavaScript + - Language feature + - Operator +translation_of: Web/JavaScript/Reference/Operators/Decrement +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>デクリメント演算子 (<code>--</code>) は、オペランドをデクリメント (1を減算) して値を返します。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-decrement.html")}}</div> + +<div></div> + + + +<h2 id="構文">構文</h2> + +<pre class="syntaxbox notranslate"><strong>Operator:</strong> <var>x</var>-- or --<var>x</var> +</pre> + +<h2 id="解説">解説</h2> + +<p>オペランドに後置で演算子を付けると (例えば <code><var>x</var>--</code>)、デクリメント演算子はデクリメントしますが、デクリメント前の値を返します。</p> + +<p>オペランドに前置で演算子を付けると (例えば <code>--<var>x</var></code>)、デクリメント演算子はデクリメントし、デクリメント後の値を返します。</p> + +<h2 id="例">例</h2> + +<h3 id="後置デクリメント">後置デクリメント</h3> + +<pre class="brush: js notranslate">let x = 3; +y = x--; + +// y = 3 +// x = 2 +</pre> + +<h3 id="前置デクリメント">前置デクリメント</h3> + +<pre class="brush: js notranslate">let a = 2; +b = --a; + +// a = 1 +// b = 1 +</pre> + +<h2 id="仕様">仕様</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">仕様</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-postfix-decrement-operator', 'Decrement operator')}}</td> + </tr> + </tbody> +</table> + +<h2 id="ブラウザーの互換性">ブラウザーの互換性</h2> + + + +<p>{{Compat("javascript.operators.decrement")}}</p> + +<h2 id="関連項目">関連項目</h2> + +<ul> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Addition">加算演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Subtraction">減算演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Multiplication">乗算演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Division">除算演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Remainder">剰余演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Exponentiation">べき乗演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Increment">インクリメント演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Unary_negation">単項マイナス演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Unary_plus">単項プラス演算子</a></li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/delete/index.html b/files/ja/web/javascript/reference/operators/delete/index.html new file mode 100644 index 0000000000..1095dd3d1c --- /dev/null +++ b/files/ja/web/javascript/reference/operators/delete/index.html @@ -0,0 +1,296 @@ +--- +title: delete +slug: Web/JavaScript/Reference/Operators/delete +tags: + - JavaScript + - Memory Management + - Object + - Operator + - Property + - Reference + - Release + - Unary + - delete +translation_of: Web/JavaScript/Reference/Operators/delete +--- +<div>{{jsSidebar("Operators")}}</div> + +<p><span class="seoSummary">JavaScript の <strong><code>delete</code> 演算子</strong>は、オブジェクトからプロパティを削除します。同じプロパティへの参照がそれ以上保持されない場合は、自動的に解放されます。</span></p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-deleteoperator.html")}}</div> + + + +<h2 id="構文">構文</h2> + +<pre class="syntaxbox notranslate">delete <em>expression</em> </pre> + +<p><em>expression</em> には、プロパティへの参照になる式を置きます。例えば:</p> + +<pre class="syntaxbox notranslate">delete <em>object.property</em> +delete <em>object</em>['<em>property</em>']</pre> + +<h3 id="引数">引数</h3> + +<dl> + <dt><code>object</code></dt> + <dd>オブジェクト名、またはオブジェクトとして評価される式</dd> + <dt><code>property</code></dt> + <dd>削除するプロパティです。</dd> +</dl> + +<h3 id="戻り値">戻り値</h3> + +<p>非 strict モードでは、プロパティが編集不可の場合、false が返ります。その他の場合すべてで <code>true</code> が返ります。</p> + +<h3 id="例外">例外</h3> + +<p><a href="/ja/docs/Web/JavaScript/Reference/Functions_and_function_scope/Strict_mode">strict モード</a> では、プロパティが編集不可の場合、{{jsxref("Global_objects/SyntaxError")}} をスローします。</p> + +<h2 id="説明">説明</h2> + +<p>一般的に信じられていることとは異なり、<code>delete</code> 演算子は、直接的にメモリを開放することは<strong>ありません</strong>。メモリの管理は参照が切れることで間接的に行われます。詳細は <a href="/ja/docs/Web/JavaScript/Memory_Management">memory management</a> をご覧ください。</p> + +<p><code><strong>delete</strong></code> 演算子は指定したプロパティをオブジェクトから取り除きます。削除に成功すると <code>true</code> を返し、そうでなければ <code>false</code> を返します。しかし、次のシナリオを考慮することが重要です:</p> + +<ul> + <li>削除しようとしたプロパティが存在しない場合、<code>delete</code> は何の効果もなく、<code>true</code> を返します。</li> + <li>同様の名前のプロパティがオブジェクトのプロトタイプチェーンに存在する場合、削除後はプロトタイプチェーンのプロパティをオブジェクトが使うようになります (つまり、<code>delete</code> 自身のプロパティにのみ効果があります)。</li> + <li>グローバルスコープや関数スコープから {{jsxref("Statements/var","var")}} で宣言されたプロパティは削除できません。 + <ul> + <li>そのため、<code>delete</code> はグローバルスコープ内の関数を削除できません (関数定義の一部であるか関数式の一部であるかにかかわらず)。</li> + <li>(グローバルスコープを除く) オブジェクトの一部である関数は <code>delete</code> で削除できます。</li> + </ul> + </li> + <li>{{jsxref("Statements/let","let")}} や {{jsxref("Statements/const","const")}} で宣言された任意のプロパティはそれらが宣言されたスコープから削除できません。</li> + <li>編集不可能なプロパティは削除できません。これには {{jsxref("Math")}} や {{jsxref("Array")}}、{{jsxref("Object")}} のようなビルトインオブジェクトのプロパティや {{jsxref("Object.defineProperty()")}} のようなメソッドで編集不可として生成されたプロパティが含まれます。</li> +</ul> + +<p>次のスニペットがシンプルな例です:</p> + +<pre class="brush: js notranslate">var Employee = { + age: 28, + name: 'abc', + designation: 'developer' +} + +console.log(delete Employee.name); // returns true +console.log(delete Employee.age); // returns true + +// When trying to delete a property that does +// not exist, true is returned +console.log(delete Employee.salary); // returns true +</pre> + +<h3 id="編集不可のプロパティ"><strong>編集不可のプロパティ</strong></h3> + +<p>プロパティが編集不可に設定されているとき、<code>delete</code> は何の効果もなく、<code>false</code> を返します。strict モードでは、これは <code>SyntaxError</code> を生成します。</p> + +<pre class="brush: js notranslate">var Employee = {}; +Object.defineProperty(Employee, 'name', {configurable: false}); + +console.log(delete Employee.name); // returns false +</pre> + +<p>{{jsxref("Statements/var","var")}} や {{jsxref("Statements/let","let")}}、{{jsxref("Statements/const","const")}} は、<code>delete</code> 演算子で削除できない編集不可のプロパティを生成します:</p> + +<pre class="brush: js notranslate">var nameOther = 'XYZ'; + +// We can access this global property using: +Object.getOwnPropertyDescriptor(window, 'nameOther'); + +// output: Object {value: "XYZ", +// writable: true, +// enumerable: true, +// <strong>configurable: false</strong>} + +// Since "nameOther" is added using with the +// var keyword, it is marked as "non-configurable" + +delete nameOther; // return false</pre> + +<p>strict モードでは、例外が発生します。</p> + +<h3 id="Strict_vs._非_strict_モード"><strong>Strict vs. 非 strict モード</strong></h3> + +<p>strict モードのとき、変数や関数の引数、関数名への参照に直接 <code>delete</code> が使われた場合、{{jsxref("SyntaxError")}} をスローします。</p> + +<p><code>var</code> で宣言された変数は編集不可に設定されます。次の例では、<code>salary</code> は編集不可で削除できません。非 strict モードでは、<code>delete</code> 演算子は <code>false</code> を返します。</p> + +<pre class="brush: js notranslate">function Employee() { + delete salary; + var salary; +} + +Employee(); +</pre> + +<p>strict モードで同じコードがどのように振る舞うか見てみましょう。<code>false</code> を返す代わりに、ステートメントは <code>SyntaxError</code> を発生させます。</p> + +<pre class="brush: js notranslate">"use strict"; + +function Employee() { + delete salary; // SyntaxError + var salary; +} + +// Similarly, any direct access to a function +// with delete will raise a SyntaxError + +function DemoFunction() { + //some code +} + +delete DemoFunction; // SyntaxError +</pre> + +<h2 id="例">例</h2> + +<pre class="brush: js notranslate">// creates the property adminName on the global scope +adminName = 'xyz'; + +// creates the property empCount on the global scope +// Since we are using var, this is marked as non-configurable. The same is true of let and const. +var empCount = 43; + +EmployeeDetails = { + name: 'xyz', + age: 5, + designation: 'Developer' +}; + +// adminName is a property of the global scope. +// It can be deleted since it is created without var. +// Therefore, it is configurable. +delete adminName; // returns true + +// On the contrary, empCount is not configurable, +// since var was used. +delete empCount; // returns false + +// delete can be used to remove properties from objects +delete EmployeeDetails.name; // returns true + +<strong>// </strong>Even when the property does not exists, it returns "true" +delete EmployeeDetails.salary; // returns true + +// delete does not affect built-in static properties +delete Math.PI; // returns false + +// EmployeeDetails is a property of the global scope. +// Since it defined without "var", it is marked configurable +delete EmployeeDetails; // returns true + +function f() { + var z = 44; + + // delete doesn't affect local variable names + delete z; // returns false +} +</pre> + +<h3 id="delete_とプロトタイプチェーン"><code>delete</code> とプロトタイプチェーン</h3> + +<p>次の例では、 <span id="result_box" lang="ja"><span>プロトタイプチェーンで同じ名前のプロパティを使用できる間に、オブジェクトの独自のプロパティを削除します</span></span> :</p> + +<pre class="brush: js notranslate">function Foo() { + this.bar = 10; +} + +Foo.prototype.bar = 42; + +var foo = new Foo(); + +// Returns true, since the own property +// has been deleted on the foo object +delete foo.bar; + +// foo.bar is still available, since it +// is available in the prototype chain. +console.log(foo.bar); + +// We delete the property on the prototype +delete Foo.prototype.bar; + +// logs "undefined" since the property +// is no longer inherited +console.log(foo.bar); </pre> + +<h3 id="配列の要素の削除"><strong>配列の要素の削除</strong></h3> + +<p>配列の要素を削除したとき、配列の長さは影響を受けません。これは配列の最後の要素を削除しても保持されます。</p> + +<p><code>delete</code> 演算子が配列の要素を削除すると、要素はもはや配列からなくなります。 次の例では、<code>trees[3]</code> が <code>delete</code> で削除されます。</p> + +<pre class="brush: js notranslate">var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple']; +delete trees[3]; +if (3 in trees) { + // this does not get executed +}</pre> + +<p>配列の要素を存在させたいが値が未定義の場合、<code>delete</code> 演算子の代わりに <code>undefined</code> 値を用います。次の例では、<code>trees[3]</code> は undefined が割り当てられていますが、配列の要素はまだ存在しています:</p> + +<pre class="brush: js notranslate">var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple']; +trees[3] = undefined; +if (3 in trees) { + // this gets executed +}</pre> + +<p>代わりに、配列の内容を変更して配列要素を削除する場合は、<code>{{jsxref("Array.splice", "splice")}}</code> メソッドを使用します。次の例では、{{jsxref("Array.splice", "splice")}} を使用して配列から <code>trees[3]</code> が削除されます:</p> + +<pre class="brush: js notranslate">var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple']; +trees.splice(3,1); +console.log(trees); // ["redwood", "bay", "cedar", "maple"] +</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('ESDraft', '#sec-delete-operator', 'The delete Operator')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-delete-operator', 'The delete Operator')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-11.4.1', 'The delete Operator')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES1', '#sec-11.4.1', 'The delete Operator')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>初期定義。JavaScript 1.2 で実装。</td> + </tr> + </tbody> +</table> + +<h2 id="ブラウザー実装状況">ブラウザー実装状況</h2> + + + +<p>{{Compat("javascript.operators.delete")}}</p> + +<h2 id="クロスブラウザーの問題点">クロスブラウザーの問題点</h2> + +<p>ECMAScript はオブジェクトのイテレーション順を実装系依存であるとしているにもかかわらず、すべての主要なブラウザーはイテレーション順を、(少なくともプロトタイプ上にないプロパティについて) 最初に追加されたプロパティを最初に持ち出す方式に基づいてサポートしているように見受けられます。ところが Internet Explorer ではプロパティに対して <code>delete</code> を用いたときに、他のブラウザーが単純なオブジェクトを整列された連想配列のように用いることを妨げる、ややこしい動作になる場合があります。Internet Explorer では、プロパティの<em>値</em>が実際 undefined に設定されているとき、後から同じ名前で再びプロパティを追加すると、そのプロパティは<em>元の</em>場所でイテレートされるようになるでしょう。削除済みのプロパティを再度追加した場合に期待するであろう、イテレーション順の最後ではありません。</p> + +<p>クロスブラウザー環境で整列された連想配列をしたい場合は、可能であれば {{jsxref("Map")}} を使用してください。または、2 つに分けた配列 (片方はキー、もう片方は値) やプロパティをひとつ持つオブジェクトの配列などで構造をシミュレートしてください。</p> + +<h2 id="関連項目">関連項目</h2> + +<ul> + <li><a href="http://perfectionkills.com/understanding-delete/">In depth analysis on delete</a></li> + <li>{{jsxref("Reflect.deleteProperty()")}}</li> + <li>{{jsxref("Map.prototype.delete()")}}</li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/destructuring_assignment/index.html b/files/ja/web/javascript/reference/operators/destructuring_assignment/index.html new file mode 100644 index 0000000000..99361d3319 --- /dev/null +++ b/files/ja/web/javascript/reference/operators/destructuring_assignment/index.html @@ -0,0 +1,444 @@ +--- +title: 分割代入 +slug: Web/JavaScript/Reference/Operators/Destructuring_assignment +tags: + - Destructuring + - Destructuring_assignment + - ECMAScript 2015 + - ES6 + - JavaScript + - Language feature + - Nested object and array destructuring + - Operator + - 分割代入 + - 演算子 +translation_of: Web/JavaScript/Reference/Operators/Destructuring_assignment +--- +<div>{{jsSidebar("Operators")}}</div> + +<p><strong>分割代入</strong> (Destructuring assignment) 構文は、配列から値を取り出して、あるいはオブジェクトからプロパティを取り出して別個の変数に代入することを可能にする JavaScript の式です。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-destructuringassignment.html", "taller")}}</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="brush:js notranslate">let a, b, rest; +[a, b] = [10, 20]; +console.log(a); // 10 +console.log(b); // 20 + +[a, b, ...rest] = [10, 20, 30, 40, 50]; +console.log(a); // 10 +console.log(b); // 20 +console.log(rest); // [30, 40, 50] + +({ a, b } = { a: 10, b: 20 }); +console.log(a); // 10 +console.log(b); // 20 + + +// Stage 4(finished) proposal +({a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40}); +console.log(a); // 10 +console.log(b); // 20 +console.log(rest); // {c: 30, d: 40} +</pre> + +<h2 id="Description" name="Description">解説</h2> + +<p>オブジェクトリテラルと配列リテラルは、いくつかのデータを<em>アドホック</em>にまとめる簡単な方法を提供します。</p> + +<pre class="brush: js notranslate">const x = [1, 2, 3, 4, 5];</pre> + +<p>分割代入は似たような構文を使用しますが、代入の左辺が元の変数からどの値を受け取るかを定義します。</p> + +<pre class="brush: js notranslate">const x = [1, 2, 3, 4, 5]; +const [y, z] = x; +console.log(y); // 1 +console.log(z); // 2 +</pre> + +<p>この機能は、Perl や Python などの言語に存在する機能に似ています。</p> + +<h2 id="Examples" name="Examples">例</h2> + +<h3 id="Array_destructuring" name="Array_destructuring">配列の分割代入</h3> + +<h4 id="Basic_variable_assignment" name="Basic_variable_assignment">簡単な例</h4> + +<pre class="brush: js notranslate">const foo = ['one', 'two', 'three']; + +const [red, yellow, green] = foo; +console.log(red); // "one" +console.log(yellow); // "two" +console.log(green); // "three" +</pre> + +<h4 id="Assignment_separate_from_declaration" name="Assignment_separate_from_declaration">宣言後の割り当て</h4> + +<p>変数は宣言とは別に、分割代入によって値を代入することができます。</p> + +<pre class="brush:js notranslate">let a, b; + +[a, b] = [1, 2]; +console.log(a); // 1 +console.log(b); // 2 +</pre> + +<h4 id="Default_values" name="Default_values">既定値</h4> + +<p>配列から取り出した値が <code>undefined</code> だった場合に使用される既定値を指定できます。</p> + +<pre class="brush: js notranslate">let a, b; + +[a=5, b=7] = [1]; +console.log(a); // 1 +console.log(b); // 7 +</pre> + +<h4 id="Swapping_variables" name="Swapping_variables">変数の入れ替え</h4> + +<p>分割代入を使用して、複数の変数の値を入れ替えることができます。</p> + +<p>分割代入を使用せずに 2 つの値を交換するには、一時変数 (または、一部の低水準言語においては <a href="https://ja.wikipedia.org/wiki/XOR%E4%BA%A4%E6%8F%9B%E3%82%A2%E3%83%AB%E3%82%B4%E3%83%AA%E3%82%BA%E3%83%A0">XOR 交換アルゴリズム</a>) が必要です。</p> + +<pre class="brush:js notranslate">let a = 1; +let b = 3; + +[a, b] = [b, a]; +console.log(a); // 3 +console.log(b); // 1 + +const arr = [1,2,3]; +[arr[2], arr[1]] = [arr[1], arr[2]]; +console.log(arr); // [1,3,2] + +</pre> + +<h4 id="Parsing_an_array_returned_from_a_function" name="Parsing_an_array_returned_from_a_function">関数から返された配列の解析</h4> + +<p>関数は配列を返すことができます。分割代入によって、返された配列の使用をより簡潔に記述できます。</p> + +<p>この例では、<code>f()</code> は出力として値 <code>[1, 2]</code> を返しており、分割代入により 1行で解析できます。</p> + +<pre class="brush:js notranslate">function f() { + return [1, 2]; +} + +let a, b; +[a, b] = f(); +console.log(a); // 1 +console.log(b); // 2 +</pre> + +<h4 id="Ignoring_some_returned_values" name="Ignoring_some_returned_values">返値の無視</h4> + +<p>関心のない返値は無視することができます。</p> + +<pre class="brush:js notranslate">function f() { + return [1, 2, 3]; +} + +const [a, , b] = f(); +console.log(a); // 1 +console.log(b); // 3 + +const [c] = f(); +console.log(c); // 1 +</pre> + +<p>このようにすべての返値を無視することもできます。</p> + +<pre class="brush:js notranslate">[,,] = f(); +</pre> + +<h4 id="Assigning_the_rest_of_an_array_to_a_variable" name="Assigning_the_rest_of_an_array_to_a_variable">配列の残余部分への変数の代入</h4> + +<p>配列を分割するときに残余パターンを使用して、配列の残りの部分を取り出して変数に代入できます。</p> + +<pre class="brush: js notranslate">const [a, ...b] = [1, 2, 3]; +console.log(a); // 1 +console.log(b); // [2, 3]</pre> + +<p>左辺側で残余要素とともに末尾のカンマが使用されていると、{{jsxref("SyntaxError")}} が発生しますので注意してください。</p> + +<pre class="brush: js example-bad notranslate">const [a, ...b,] = [1, 2, 3]; + +// SyntaxError: rest 要素の末尾にカンマがあってはなりません +// 常に最後の要素として rest 演算子を使用してください。 +</pre> + +<h4 id="Unpacking_values_from_a_regular_expression_match" name="Unpacking_values_from_a_regular_expression_match">正規表現の一致からの値取得</h4> + +<p>正規表現オブジェクトの <code><a href="/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec"> exec()</a></code> メソッドは一致するものを見つけ、最初に一致した文字列全体の一部と、正規表現内の各括弧で囲まれたグループに一致した文字列の部分を含む配列を返します。分割代入によって、簡単にこの配列の一部分を取り出せます。また必要でない場合は、完全一致を無視できます。</p> + +<pre class="brush:js notranslate">function parseProtocol(url) { + const parsedURL = /^(\w+)\:\/\/([^\/]+)\/(.*)$/.exec(url); + if (!parsedURL) { + return false; + } + console.log(parsedURL); + // ["https://developer.mozilla.org/ja/Web/JavaScript", + "https", "developer.mozilla.org", "en-US/Web/JavaScript"] + + const [, protocol, fullhost, fullpath] = parsedURL; + return protocol; +} + +console.log(parseProtocol('https://developer.mozilla.org/ja/Web/JavaScript')); +// "https" +</pre> + +<h3 id="Object_destructuring" name="Object_destructuring">オブジェクトの分割代入</h3> + +<h4 id="Basic_assignment" name="Basic_assignment">簡単な例</h4> + +<pre class="brush: js notranslate">const user = { + id: 42, + is_verified: true +}; + +const {id, is_verified} = user; + +console.log(id); // 42 +console.log(is_verified); // true +</pre> + +<h4 id="Assignment_without_declaration" name="Assignment_without_declaration">宣言のない代入</h4> + +<p>分割代入は代入文で宣言することなく行うことができます。</p> + +<pre class="brush:js notranslate">let a, b; + +({a, b} = {a: 1, b: 2});</pre> + +<div class="note"> +<p><strong>メモ</strong>: 代入文の周りの <code>( ... )</code> は宣言のないオブジェクトリテラル分割代入を使用するときに必要な構文です。</p> + +<p><code>{a, b} = {a: 1, b: 2}</code> は有効なスタンドアロンの構文ではありません。というのも、左辺の <code>{a, b}</code> はブロックでありオブジェクトリテラルではないと考えられるからです。</p> + +<p>ですが、<code>({a, b} = {a: 1, b: 2})</code> 形式は有効です。<code>var {a, b} = {a: 1, b: 2}</code> と考えられるためです。</p> + +<p><code>( ... )</code> の式の前にセミコロンが必要です。そうしなければ、前の行の関数を実行に使用される可能性があります。</p> +</div> + +<h4 id="Assigning_to_new_variable_names" name="Assigning_to_new_variable_names">異なる名前を持つ変数への代入</h4> + +<p>オブジェクトから変数を取り出して、オブジェクトのプロパティとは異なる名前の変数に代入することができます。</p> + +<pre class="brush: js notranslate">const o = {p: 42, q: true}; +const {p: foo, q: bar} = o; + +console.log(foo); // 42 +console.log(bar); // true</pre> + +<p>ここで、例えば、<code>const {p: foo} = o</code> はオブジェクト <code>o</code> から <code>p</code> という名前のプロパティを取り、<code>foo</code> という名前のローカル変数へ代入します。</p> + +<h4 id="Default_values_2" name="Default_values_2">既定値</h4> + +<p>オブジェクトから取り出した値が <code>undefined</code> であるときの既定値を、変数に割り当てることができます。</p> + +<pre class="brush: js notranslate">var {a = 10, b = 5} = {a: 3}; + +console.log(a); // 3 +console.log(b); // 5</pre> + +<h4 id="Assigning_to_new_variables_names_and_providing_default_values" name="Assigning_to_new_variables_names_and_providing_default_values">新しい変数名の割り当てとデフォルト値の提供</h4> + +<p>両方ともプロパティにすることができます</p> + +<ul> + <li>オブジェクトから取り出して異なる名前の変数に代入します。</li> + <li>取り出した値が <code>undefined</code> である場合に備えて、デフォルト値を割り当てます。</li> +</ul> + +<pre class="brush: js notranslate">const {a: aa = 10, b: bb = 5} = {a: 3}; + +console.log(aa); // 3 +console.log(bb); // 5 +</pre> + +<h4 id="Unpacking_fields_from_objects_passed_as_function_parameter" name="Unpacking_fields_from_objects_passed_as_function_parameter">引数に指定されたオブジェクトの属性への参照</h4> + +<pre class="brush:js notranslate">const user = { + id: 42, + displayName: 'jdoe', + fullName: { + firstName: 'John', + lastName: 'Doe' + } +}; + +function userId({id}) { + return id; +} + +function whois({displayName, fullName: {firstName: name}}) { + return `${displayName} is ${name}`; +} + +console.log(userId(user)); // 42 +console.log(whois(user)); // "jdoe is John"</pre> + +<p>上記では <code>id</code>, <code>displayName</code>, <code>firstName</code> をオブジェクトから取得し、出力します。</p> + +<h4 id="Setting_a_function_parameters_default_value" name="Setting_a_function_parameters_default_value">関数の引数に対する既定値の設定</h4> + +<pre class="brush: js notranslate">function drawChart({size = 'big', coords = {x: 0, y: 0}, radius = 25} = {}) { + console.log(size, coords, radius); + // グラフの描画 +} + +drawChart({ + coords: {x: 18, y: 30}, + radius: 30 +});</pre> + +<div class="note"> +<p>上記の <strong><code>drawChart</code></strong> の関数シグネチャの中で、<code>{size = 'big', coords = {x: 0, y: 0}, radius = 25} = {}</code> として、分割代入の左辺に、右辺側で空のオブジェクトリテラルを代入しています。右辺の代入がない関数を記入することもできます。しかし、右辺の代入を取り除いた場合、関数は実行されたときに少なくともひとつの引数が提供されることを期待しますが、この形式では何も引数を指定せずに単純に <code><strong>drawChart()</strong></code> を呼び出すことができます。この設計は引数を指定せずに関数を呼び出せるようにしたい場合に役に立ちますし、もう一方の形式は、オブジェクトを確実に関数に渡したい場合に役に立ちます。</p> +</div> + +<h4 id="Nested_object_and_array_destructuring" name="Nested_object_and_array_destructuring">入れ子になったオブジェクトと配列の分割代入</h4> + +<pre class="brush:js notranslate">const metadata = { + title: 'Scratchpad', + translations: [ + { + locale: 'de', + localization_tags: [], + last_edit: '2014-04-14T08:43:37', + url: '/de/docs/Tools/Scratchpad', + title: 'JavaScript-Umgebung' + } + ], + url: '/en-US/docs/Tools/Scratchpad' +}; + +let { + title: englishTitle, // rename + translations: [ + { + title: localeTitle, // rename + }, + ], +} = metadata; + +console.log(englishTitle); // "Scratchpad" +console.log(localeTitle); // "JavaScript-Umgebung"</pre> + +<h4 id="For_of_iteration_and_destructuring" name="For_of_iteration_and_destructuring">イテレーターでの分割代入の利用</h4> + +<pre class="brush: js notranslate">const people = [ + { + name: 'Mike Smith', + family: { + mother: 'Jane Smith', + father: 'Harry Smith', + sister: 'Samantha Smith' + }, + age: 35 + }, + { + name: 'Tom Jones', + family: { + mother: 'Norah Jones', + father: 'Richard Jones', + brother: 'Howard Jones' + }, + age: 25 + } +]; + +for (const {name: n, family: {father: f}} of people) { + console.log('Name: ' + n + ', Father: ' + f); +} + +// "Name: Mike Smith, Father: Harry Smith" +// "Name: Tom Jones, Father: Richard Jones" +</pre> + +<h4 id="Computed_object_property_names_and_destructuring" name="Computed_object_property_names_and_destructuring">計算されたオブジェクトのプロパティの名前と分割代入</h4> + +<p><a href="/ja/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names">オブジェクトリテラル</a>のような計算されたプロパティの名前も分割代入で使用できます。</p> + +<pre class="brush: js notranslate">let key = 'z'; +let {[key]: foo} = {z: 'bar'}; + +console.log(foo); // "bar" +</pre> + +<h4 id="Rest_in_Object_Destructuring" name="Rest_in_Object_Destructuring">オブジェクトの分割代入の残り</h4> + +<p><a class="external external-icon" href="https://github.com/tc39/proposal-object-rest-spread">Rest/Spread Properties for ECMAScript</a> 提案 (ステージ 4) は、分割代入に <a href="/ja/docs/Web/JavaScript/Reference/Functions/rest_parameters">rest</a> 構文を追加しています。残余プロパティは、分割パターンによってすでに取り出されていない、残りの列挙可能なプロパティのキーを収集します。</p> + +<pre class="brush: js notranslate">let {a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40} +a; // 10 +b; // 20 +rest; // { c: 30, d: 40 }</pre> + +<h4 id="Invalid_JavaScript_identifier_as_a_property_name" name="Invalid_JavaScript_identifier_as_a_property_name">無効な JavaScript 識別子をプロパティ名として使用する</h4> + +<p>JavaScript で有効な代替識別子を与えることにより、JavaScript で有効ではない{{glossary("Identifier", "識別子")}}であるプロパティ名を分割代入で使用できます。</p> + +<pre class="brush: js notranslate">const foo = { 'fizz-buzz': true }; +const { 'fizz-buzz': fizzBuzz } = foo; + +console.log(fizzBuzz); // "true" +</pre> + +<h4 id="Combined_Array_and_Object_Destructuring" name="Combined_Array_and_Object_Destructuring">配列とオブジェクトの分割代入の組み合わせ</h4> + +<p>配列とオブジェクトの分割代入は組み合わせることができます。配列 <code>props</code> の 3 番目の要素にあるオブジェクトの <code>name</code> プロパティが欲しい場合、次の操作ができます。</p> + +<pre class="brush: js notranslate">const props = [ + { id: 1, name: 'Fizz'}, + { id: 2, name: 'Buzz'}, + { id: 3, name: 'FizzBuzz'} +]; + +const [,, { name }] = props; + +console.log(name); // "FizzBuzz" +</pre> + +<h4 id="The_prototype_chain_is_looked_up_when_the_object_is_deconstructed" name="The_prototype_chain_is_looked_up_when_the_object_is_deconstructed">オブジェクトが分割されるときにはプロトタイプチェーンが参照される</h4> + +<p>オブジェクトが分割されるときで、自分自身のプロパティがアクセスされない場合は、プロトタイプチェーンを辿って参照が続けられます。</p> + +<pre class="brush: js notranslate">let obj = {self: '123'}; +obj.__proto__.prot = '456'; +const {self, prot} = obj; +// self "123" +// prot "456"(プロトタイプチェーンへのアクセス)</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-destructuring-assignment', 'Destructuring assignment')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">ブラウザーの互換性</h2> + +<div> +<div class="hidden">このページの互換性一覧表は構造化データから生成されています。データに協力していただけるのであれば、<a class="external" href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> をチェックアウトしてプルリクエストを送信してください。</div> + +<p>{{Compat("javascript.operators.destructuring")}}</p> +</div> + +<h2 id="See_also" name="See_also">関連情報</h2> + +<ul> + <li><a href="/ja/docs/Web/JavaScript/Reference/Operators/Assignment_Operators">代入演算子</a></li> + <li><a href="https://hacks.mozilla.org/2015/05/es6-in-depth-destructuring/">"ES6 in Depth: Destructuring" on hacks.mozilla.org</a></li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/division/index.html b/files/ja/web/javascript/reference/operators/division/index.html new file mode 100644 index 0000000000..e3fd9b96f9 --- /dev/null +++ b/files/ja/web/javascript/reference/operators/division/index.html @@ -0,0 +1,76 @@ +--- +title: 除算 (/) +slug: Web/JavaScript/Reference/Operators/Division +tags: + - JavaScript + - Language feature + - Operator + - Reference +translation_of: Web/JavaScript/Reference/Operators/Division +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>除算演算子 (<code>/</code>) は、左のオペランドを被除数とし右のオペランドを除数としたオペランド同士の商を生成します。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-division.html")}}</div> + +<div></div> + + + +<h2 id="構文">構文</h2> + +<pre class="syntaxbox notranslate"><strong>Operator:</strong> <var>x</var> / <var>y</var> +</pre> + +<h2 id="例">例</h2> + +<h3 id="基本の除算">基本の除算</h3> + +<pre class="brush: js notranslate">1 / 2 // 0.5 + +Math.floor(3 / 2) // 1 + +1.0 / 2.0 // 0.5 +</pre> + +<h3 id="ゼロ除算">ゼロ除算</h3> + +<pre class="brush: js notranslate">2.0 / 0 // Infinity + +2.0 / 0.0 // Infinity, because 0.0 === 0 + +2.0 / -0.0 // -Infinity</pre> + +<h2 id="仕様">仕様</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">仕様</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-multiplicative-operators', 'Division operator')}}</td> + </tr> + </tbody> +</table> + +<h2 id="ブラウザーの互換性">ブラウザーの互換性</h2> + + + +<p>{{Compat("javascript.operators.division")}}</p> + +<h2 id="関連項目">関連項目</h2> + +<ul> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Addition">加算演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Subtraction">減算演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Multiplication">乗算演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Remainder">剰余演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Exponentiation">べき乗演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Increment">インクリメント演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Decrement">デクリメント演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Unary_negation">単項マイナス演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Unary_plus">単項プラス演算子</a></li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/division_assignment/index.html b/files/ja/web/javascript/reference/operators/division_assignment/index.html new file mode 100644 index 0000000000..f00c9d14c8 --- /dev/null +++ b/files/ja/web/javascript/reference/operators/division_assignment/index.html @@ -0,0 +1,63 @@ +--- +title: 除算代入 (/=) +slug: Web/JavaScript/Reference/Operators/Division_assignment +tags: + - Assignment operator + - JavaScript + - Language feature + - Operator + - Reference + - 代入演算子 + - 演算子 + - 言語機能 +translation_of: Web/JavaScript/Reference/Operators/Division_assignment +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>除算代入演算子 (<code>/=</code>) は変数を右オペランドの値で除算し、結果をその変数に代入するものです。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-division-assignment.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"><strong>演算子:</strong> x /= y +<strong>意味:</strong> x = x / y</pre> + +<h2 id="Examples" name="Examples">例</h2> + +<h3 id="Using_division_assignment" name="Using_division_assignment">除算代入の使用</h3> + +<pre class="brush: js notranslate">// 以下の変数があると想定する +// bar = 5 + +bar /= 2 // 2.5 +bar /= 'foo' // NaN +bar /= 0 // Infinity</pre> + +<h2 id="Specifications" name="Specifications">仕様書</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">仕様書</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-assignment-operators', 'Assignment operators')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">ブラウザーの互換性</h2> + +<div class="hidden">このページの互換性一覧表は構造化データから生成されています。データに協力していただけるのであれば、 <a class="external" href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> をチェックアウトしてプルリクエストを送信してください。</div> + +<p>{{Compat("javascript.operators.division_assignment")}}</p> + +<h2 id="See_also" name="See_also">関連情報</h2> + +<ul> + <li><a href="/ja/docs/Web/JavaScript/Guide/Expressions_and_Operators#Assignment">JavaScript ガイドの代入演算子</a></li> + <li><a href="/ja/docs/Web/JavaScript/Reference/Operators/Division">除算演算子</a></li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/equality/index.html b/files/ja/web/javascript/reference/operators/equality/index.html new file mode 100644 index 0000000000..b1fdee1943 --- /dev/null +++ b/files/ja/web/javascript/reference/operators/equality/index.html @@ -0,0 +1,128 @@ +--- +title: 等価 (==) +slug: Web/JavaScript/Reference/Operators/Equality +tags: + - JavaScript + - Language feature + - Operator + - Reference + - 演算子 + - 言語機能 +translation_of: Web/JavaScript/Reference/Operators/Equality +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>等価演算子 (<code>==</code>) は、二つのオペランドが等しいことを検査し、論理値で結果を返します <a href="/ja/docs/Web/JavaScript/Reference/Operators/Strict_equality">厳密等価</a>演算子とは異なり、オペランドの型が異なる場合には型の変換を試みてから比較を行います。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-equality.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">x == y +</pre> + +<h2 id="Description" name="Description">解説</h2> + +<p>等価演算子 (<code>==</code> および <code>!=</code>) は、<a href="http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3">抽象等価比較アルゴリズム</a>を使用して二つのオペランドを比較します。これは、およそ次のようにまとめることができます。</p> + +<ul> + <li>両方のオペランドがオブジェクトである場合、同じオブジェクトを指している場合に限り <code>true</code> を返します。</li> + <li>一方のオペランドが <code>null</code> で、もう一方が <code>undefined</code> であった場合は <code>true</code> を返します。</li> + <li>オペランドの型が異なる場合は、比較前に同じ型に変換を試みます。 + <ul> + <li>数値と文字列を比較する場合、文字列を数値に変換しようとします。</li> + <li>一方のオペランドが <code>Boolean</code> である場合、その Boolean のオペランドが <code>true</code> である場合は 1 に、 <code>false</code> である場合は +0 に変換します。</li> + <li>オペランドのうちの1つがオブジェクトで、もう一方が数値または文字列である場合は、そのオブジェクトの <code>valueOf()</code> および <code>toString()</code> メソッドを使用してプリミティブに変換しようとします。</li> + </ul> + </li> + <li>オペランドが同じ型である場合は、次のよう比較します。 + <ul> + <li><code>String</code>: 両方のオペランドが同じ文字を同じ順序で持っている場合のみ、 <code>true</code> を返します。</li> + <li><code>Number</code>: 数値型は同じ値の数値である場合のみ、 <code>true</code> を返します。 <code>+0</code> と <code>-0</code> は同じ値と見なされます。一方のオペランドが <code>NaN</code> である場合は <code>false</code> を返します。</li> + <li><code>Boolean</code>: 両方のオペランドが共に <code>true</code> であるか、共に <code>false</code> である場合のみ <code>true</code> になります。</li> + </ul> + </li> +</ul> + +<p>この演算子と<a href="/ja/docs/Web/JavaScript/Reference/Operators/Strict_equality">厳密等価</a> (<code>===</code>) 演算子の最も顕著な違いは、厳密等価演算子が型変換を試みない点です。厳密等価演算は、オペランドの型が異なる場合は常に異なるものと見なします。</p> + +<h2 id="Examples" name="Examples">例</h2> + +<h3 id="Comparison_with_no_type_conversion" name="Comparison_with_no_type_conversion">型変換がない場合の比較</h3> + +<pre class="brush: js notranslate">1 == 1; // true +"hello" == "hello"; // true</pre> + +<h3 id="Comparison_with_type_conversion" name="Comparison_with_type_conversion">型変換がある場合の比較</h3> + +<pre class="brush: js notranslate">"1" == 1; // true +1 == "1"; // true +0 == false; // true +0 == null; // false +0 == undefined; // false +null == undefined; // true + +const number1 = new Number(3); +const number2 = new Number(3); +number1 == 3; // true +number1 == number2; // false</pre> + +<h3 id="オブジェクトの比較">オブジェクトの比較</h3> + +<pre class="brush: js notranslate">const object1 = {"key": "value"} +const object2 = {"key": "value"}; + +object1 == object2 // false +object2 == object2 // true</pre> + +<h3 id="Comparing_strings_and_String_objects" name="Comparing_strings_and_String_objects">文字列と String オブジェクトの比較</h3> + +<p><code>new String()</code> を使用して構築された文字列はオブジェクトであることに注意してください。文字列リテラルとの比較を行うと、 <code>String</code> オブジェクトは文字列リテラルに変換され、その中身が比較されます。ただし、両方のオペランドが <code>String</code> オブジェクトであった場合は、オブジェクトとして比較され、同じオブジェクトを参照している場合だけ比較に成功します。</p> + +<pre class="brush: js notranslate">const string1 = "hello"; +const string2 = String("hello"); +const string3 = new String("hello"); +const string4 = new String("hello"); + +console.log(string1 == string2); // true +console.log(string1 == string3); // true +console.log(string2 == string3); // true +console.log(string3 == string4); // false +console.log(string4 == string4); // true</pre> + +<h3 id="Comparing_Dates_and_strings" name="Comparing_Dates_and_strings">Date と文字列の比較</h3> + +<pre class="brush: js notranslate">const d = new Date('December 17, 1995 03:24:00'); +const s = d.toString(); // for example: "Sun Dec 17 1995 03:24:00 GMT-0800 (Pacific Standard Time)" +console.log(d == s); //true</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-equality-operators', 'Equality operators')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">ブラウザーの互換性</h2> + +<div class="hidden">このページの互換性一覧表は構造化データから生成されています。データに協力していただけるのであれば、 <a class="external" href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> をチェックアウトしてプルリクエストを送信してください。</div> + +<p>{{Compat("javascript.operators.strict_inequality")}}</p> + +<h2 id="See_also" name="See_also">関連情報</h2> + +<ul> + <li><a href="/ja/docs/Web/JavaScript/Reference/Operators/Inequality">不等価演算子</a></li> + <li><a href="/ja/docs/Web/JavaScript/Reference/Operators/Strict_equality">厳密等価演算子</a></li> + <li><a href="/ja/docs/Web/JavaScript/Reference/Operators/Strict_inequality">厳密不等価演算子</a></li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/exponentiation/index.html b/files/ja/web/javascript/reference/operators/exponentiation/index.html new file mode 100644 index 0000000000..8a3e13a8b1 --- /dev/null +++ b/files/ja/web/javascript/reference/operators/exponentiation/index.html @@ -0,0 +1,103 @@ +--- +title: べき乗 (**) +slug: Web/JavaScript/Reference/Operators/Exponentiation +tags: + - JavaScript + - Language feature + - Operator + - Reference +translation_of: Web/JavaScript/Reference/Operators/Exponentiation +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>べき乗演算子 (<code>**</code>) は、1番目のオペランドを2番目のオペランドの累乗まで上げた結果を返します。これは <code>Math.pow</code> と同等ですが、オペランドとして <a href="/docs/Web/JavaScript/Data_structures#BigInt_%E5%9E%8B">BigInt</a> も受け入れます。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-exponentiation.html")}}</div> + + + +<h2 id="構文">構文</h2> + +<pre class="syntaxbox notranslate"><strong>Operator:</strong> <var>var1</var> ** <var>var2</var> +</pre> + +<h2 id="説明">説明</h2> + +<p>べき乗演算子は右結合的です: <code><var>a</var> ** <var>b</var> ** <var>c</var></code> は <code><var>a</var> ** (<var>b</var> ** <var>c</var>)</code> と等しくなります。</p> + +<p>PHP や Python など、べき乗演算子 (<code>**</code>) を持つほとんどの言語では、べき乗演算子は単項演算子 (単項演算子 <code>+</code> や単項演算子 <code>-</code> など) よりも優先順位が高いと定義されていますが、いくつかの例外があります。例えば、Bash では <code>**</code> 演算子は単項演算子よりも優先順位が低いと定義されています。</p> + +<p>JavaScriptでは、あいまいなべき乗式を記述することはできません。 つまり、基数の直前に単項演算子 (<code>+/-/~/!/delete/void/typeof</code>) を置くことはできません。 これを行うと、SyntaxError が発生します。</p> + +<pre class="brush: js notranslate">-2 ** 2; +// Bashでは 4 他の言語では -4 +// JavaScriptでは意図があいまいなため無効 + + +-(2 ** 2); +// JavaScriptでは意図が明白なため -4 +</pre> + +<p>注意: 一部のプログラミング言語ではべき乗計算にキャレット記号 <kbd>^</kbd> を使用していますが、JavaScript では<a href="/docs/Web/JavaScript/Reference/Operators/Bitwise_XOR">ビット排他的論理和</a>にこの記号を使用しています。</p> + +<h2 id="例">例</h2> + +<h3 id="基本的なべき乗">基本的なべき乗</h3> + +<pre class="brush: js notranslate">2 ** 3 // 8 +3 ** 2 // 9 +3 ** 2.5 // 15.588457268119896 +10 ** -1 // 0.1 +NaN ** 2 // NaN +</pre> + +<h3 id="結合">結合</h3> + +<pre class="brush: js notranslate">2 ** 3 ** 2 // 512 +2 ** (3 ** 2) // 512 +(2 ** 3) ** 2 // 64</pre> + +<h3 id="単項演算子との使用">単項演算子との使用</h3> + +<p>べき乗式の結果の符号を反転させる</p> + +<pre class="brush: js notranslate">-(2 ** 2) // -4 +</pre> + +<p>べき乗式の基底を強制的に負の数にする</p> + +<pre class="brush: js notranslate">(-2) ** 2 // 4 +</pre> + +<h2 id="仕様">仕様</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">仕様書</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-exp-operator', 'Exponentiation operator')}}</td> + </tr> + </tbody> +</table> + +<h2 id="ブラウザの互換性">ブラウザの互換性</h2> + + + +<p>{{Compat("javascript.operators.exponentiation")}}</p> + +<h2 id="関連情報">関連情報</h2> + +<ul> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Addition">加算演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Subtraction">減算演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Multiplication">乗算演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Division">除算演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Remainder">剰余演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Increment">インクリメント演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Decrement">デクリメント演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Unary_negation">単項マイナス演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Unary_plus">単項プラス演算子</a></li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/exponentiation_assignment/index.html b/files/ja/web/javascript/reference/operators/exponentiation_assignment/index.html new file mode 100644 index 0000000000..fa942f4779 --- /dev/null +++ b/files/ja/web/javascript/reference/operators/exponentiation_assignment/index.html @@ -0,0 +1,61 @@ +--- +title: べき乗代入 (**=) +slug: Web/JavaScript/Reference/Operators/Exponentiation_assignment +tags: + - Assignment operator + - JavaScript + - Language feature + - Operator + - Reference +translation_of: Web/JavaScript/Reference/Operators/Exponentiation_assignment +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>べき乗代入演算子 (<code>**=</code>) は、変数の値を右辺のオペランドでべき乗します。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-exponentiation-assignment.html")}}</div> + +<div></div> + + + +<h2 id="構文">構文</h2> + +<pre class="syntaxbox notranslate"><strong>Operator:</strong> x **= y +<strong>Meaning:</strong> x = x ** y</pre> + +<h2 id="例">例</h2> + +<h3 id="べき乗代入の仕様">べき乗代入の仕様</h3> + +<pre class="brush: js notranslate">// 次の変数を想定 +// bar = 5 + +bar **= 2 // 25 +bar **= 'foo' // NaN</pre> + +<h2 id="仕様">仕様</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">仕様</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-assignment-operators', 'Assignment operators')}}</td> + </tr> + </tbody> +</table> + +<h2 id="ブラウザー実装状況">ブラウザー実装状況</h2> + + + +<p>{{Compat("javascript.operators.exponentiation_assignment")}}</p> + +<h2 id="関連項目">関連項目</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Assignment">Assignment operators in the JS guide</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Exponentiation">Exponentiation operator</a></li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/expression_closures/index.html b/files/ja/web/javascript/reference/operators/expression_closures/index.html new file mode 100644 index 0000000000..6b0df0f858 --- /dev/null +++ b/files/ja/web/javascript/reference/operators/expression_closures/index.html @@ -0,0 +1,76 @@ +--- +title: 式クロージャ +slug: Web/JavaScript/Reference/Operators/Expression_closures +tags: + - Functions + - JavaScript + - Reference +translation_of: Archive/Web/JavaScript/Expression_closures +--- +<div class="warning"><strong>非標準。使用しないでください!</strong><br> +式クロージャの構文は、非推奨とされた Firefox 固有の機能であり、Firefox Firefox 60 で削除されました。将来向きの用途には、<a href="/docs/Web/JavaScript/Reference/Functions/Arrow_functions">アロー関数</a> の使用を検討してください。</div> + +<div>{{jsSidebar("Operators")}}</div> + +<p>式クロージャは、単純な関数を書くための短縮された関数構文です。</p> + +<h2 id="構文">構文</h2> + +<pre class="syntaxbox">function [<em>name</em>]([<em>param1</em>[, <em>param2[</em>, ..., <em>paramN</em>]]]) + <em>expression</em> +</pre> + +<h3 id="引数">引数</h3> + +<dl> + <dt><code>name</code></dt> + <dd>関数名。関数が <em>匿名</em> の場合、省略できます。名前は関数本体だけのローカルです。</dd> + <dt><code>paramN</code></dt> + <dd>関数に渡される引数の名前。関数は、最大 255 個の引数を持つことができます。</dd> + <dt><code>expression</code></dt> + <dd>関数本体を構成する式。</dd> +</dl> + +<h2 id="説明">説明</h2> + +<p>これは、単純な関数を書くための短縮された関数構文にすぎません。典型的な <a class="external" href="http://en.wikipedia.org/wiki/Lambda_calculus#Lambda_calculus_and_programming_languages">Lambda 表記</a> に似た言語で書くためのものです。</p> + +<p>JavaScript 1.7 およびそれ以前:</p> + +<pre class="brush: js">function(x) { return x * x; }</pre> + +<p>JavaScript 1.8:</p> + +<pre class="brush: js">function(x) x * x</pre> + +<p>この構文により、中括弧と 'return' 文をなくします (それらは暗黙的に宣言されています)。構文が短くなること以外に、このようにコードを書くことへの付加的な利点はありません。</p> + +<h2 id="例">例</h2> + +<p>イベントリスナをバインドする短縮表現:</p> + +<pre class="brush: js">document.addEventListener("click", function() false, true); +</pre> + +<p>JavaScript 1.6 から、配列関数の一部でこの表記法を用います:</p> + +<pre class="brush: js">elems.some(function(elem) elem.type == "text"); +</pre> + +<h2 id="ブラウザの実装状況">ブラウザの実装状況</h2> + + + +<p>{{Compat("javascript.operators.expression_closures")}}</p> + +<h2 id="関連情報">関連情報</h2> + +<ul> + <li>{{jsxref("Functions_and_function_scope", "関数と関数のスコープ")}}</li> + <li>{{jsxref("Function")}}</li> + <li>{{jsxref("Statements/function", "function statement")}}</li> + <li>{{jsxref("Operators/function", "function expression")}}</li> + <li>{{jsxref("Statements/function*", "function* statement")}}</li> + <li>{{jsxref("Operators/function*", "function* expression")}}</li> + <li>{{jsxref("GeneratorFunction")}}</li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/function/index.html b/files/ja/web/javascript/reference/operators/function/index.html new file mode 100644 index 0000000000..5ea0b7ffbc --- /dev/null +++ b/files/ja/web/javascript/reference/operators/function/index.html @@ -0,0 +1,145 @@ +--- +title: 関数式 +slug: Web/JavaScript/Reference/Operators/function +tags: + - Function + - JavaScript + - Language feature + - Operator + - Primary Expressions + - 演算子 + - 言語機能 +translation_of: Web/JavaScript/Reference/Operators/function +--- +<div>{{jsSidebar("Operators")}}</div> + +<p><strong><code>function</code></strong> キーワードは、式の中で関数を定義するために使用されます。</p> + +<p>{{jsxref("Function/Function", "Function")}} コンストラクターや{{jsxref("Statements/function", "関数宣言", "", 1)}}を用いて関数を定義することもできます。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-functionexpression.html", "shorter")}}</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">let <var>myFunction</var> = function [<var>name</var>]([<var>param1</var>[, <var>param2[</var>, ..., <var>paramN</var>]]]) { + <var>statements</var> +};</pre> + +<p>ES2015 からは{{jsxref("Functions/Arrow_functions", "アロー関数", "", 1)}}も使えます。</p> + +<h3 id="Parameters" name="Parameters">引数</h3> + +<dl> + <dt><code><var>name</var></code> {{optional_inline}}</dt> + <dd>関数名。省略可能で、その場合は関数は<em>無名</em>になります。 name は関数本体のみのローカルです。</dd> + <dt><code><var>paramN</var></code> {{optional_inline}}</dt> + <dd>関数に渡される引数の名前です。</dd> + <dt><code><var>statements</var></code> {{optional_inline}}</dt> + <dd>関数の本体を構成する文です。</dd> +</dl> + +<h2 id="Description" name="Description">解説</h2> + +<p>関数式は関数宣言とよく似ており、ほとんど同じ書式でもあります (詳しくは {{jsxref("Statements/function", "function")}} 文を参照してください)。関数式と関数宣言の主な相違点は、<em>関数名</em>です。関数式では、<em>無名</em>関数を生成するために、関数名を省略できます。関数式は、定義するとすぐに実行する <strong>IIFE</strong> (即時実行関数)として使用できます。詳細については、{{jsxref("Functions", "関数", "", 1)}}の章を参照してください。</p> + +<h3 id="Function_expression_hoisting" name="Function_expression_hoisting">関数式の巻き上げ</h3> + +<p>JavaScript の関数式は、{{jsxref("Statements/function", "関数宣言", "#Function_declaration_hoisting", 1)}}と違って巻き上げられません。定義前に関数式を使用することはできません。</p> + +<pre class="brush: js">console.log(notHoisted) // undefined +// 変数名は巻き上げが行われますが、定義は行われません。そのため undefined になります。 +notHoisted(); // TypeError: notHoisted is not a function + +var notHoisted = function() { + console.log('bar'); +}; +</pre> + +<h3 id="Named_function_expression" name="Named_function_expression">名前付き関数式</h3> + +<p>関数内でその関数自身を参照する必要がある場合は、名前付き関数式を作成する必要があります。<u><strong>この名前は関数本体 (スコープ) に対してのみローカルです</strong></u>。これにより非標準の {{jsxref("Functions/arguments/callee", "arguments.callee")}} プロパティの使用も避けられます。</p> + +<pre class="brush: js">let math = { + 'factit': function factorial(n) { + console.log(n) + if (n <= 1) { + return 1; + } + return n * factorial(n - 1); + } +}; + +math.factit(3) //3;2;1; +</pre> + +<p>関数式が代入された変数は <code>name</code> プロパティを持ちます。別の変数に代入しても name は変わりません。関数名が省略された場合、変数名になります (暗黙的gな名前)。関数名が存在したら、それが関数名になります (明示的な名前)。これは{{jsxref("Functions/Arrow_functions", "アロー関数", "", 1)}}にもあてはまります (アローは名前がないので変数名を暗黙的な名前として与える)。</p> + +<pre class="brush: js">var foo = function() {} +foo.name // "foo" + +var foo2 = foo +foo2.name // "foo" + +var bar = function baz() {} +bar.name // "baz" + +console.log(foo === foo2); // true +console.log(typeof baz); // undefined +console.log(bar === baz); // false (errors because baz == undefined) +</pre> + +<h2 id="Examples" name="Examples">例</h2> + +<h3 id="Creating_an_unnamed_function" name="Creating_an_unnamed_function">無名関数の作成</h3> + +<p>次の例では、無名関数を定義してそれを <code>x</code> に割り当てます。 関数は引数の 2 乗を返します。</p> + +<pre class="brush: js">var x = function(y) { + return y * y; +}; +</pre> + +<h3 id="Using_a_function_as_a_callback" name="Using_a_function_as_a_callback">関数をコールバックとして使用</h3> + +<p>より一般的には{{Glossary("Callback_function", "コールバック")}}として使われます。</p> + +<pre class="brush: js">button.addEventListener('click', function(event) { + console.log('button is clicked!') +})</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-function-definitions', 'Function definitions')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">ブラウザーの互換性</h2> + +<div class="hidden">このページの互換性一覧表は構造化データから生成されています。データに協力していただけるのであれば、 <a class="external" href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> をチェックアウトしてプルリクエストを送信してください。</div> + +<p>{{Compat("javascript.operators.function")}}</p> + +<h2 id="See_also" name="See_also">関連情報</h2> + +<ul> + <li>{{jsxref("Arrow_functions", "アロー関数", "", 1)}}</li> + <li>{{jsxref("Functions_and_function_scope", "関数と関数スコープ", "", 1)}}</li> + <li>{{jsxref("Function")}}</li> + <li>{{jsxref("Statements/function", "function")}} 文</li> + <li>{{jsxref("Statements/function*", "function*")}} 文</li> + <li>{{jsxref("Operators/function*", "function*")}} 式</li> + <li>{{jsxref("GeneratorFunction")}}</li> + <li>{{jsxref("Statements/async_function", "非同期関数", "", 1)}}</li> + <li>{{jsxref("Operators/async_function", "非同期関数式", "", 1)}}</li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/function_star_/index.html b/files/ja/web/javascript/reference/operators/function_star_/index.html new file mode 100644 index 0000000000..669955b169 --- /dev/null +++ b/files/ja/web/javascript/reference/operators/function_star_/index.html @@ -0,0 +1,88 @@ +--- +title: function* 式 +slug: Web/JavaScript/Reference/Operators/function* +tags: + - ECMAScript6 + - Function + - Iterator + - JavaScript + - Operator + - Primary Expression + - 演算子 + - 関数 +translation_of: Web/JavaScript/Reference/Operators/function* +--- +<div>{{jsSidebar("Operators")}}</div> + +<p><strong><code>function*</code></strong> キーワードは、式の中でジェネレーター関数を定義するために使用することができます。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-functionasteriskexpression.html", "taller")}}</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">function* [<var>name</var>]([<var>param1</var>[, <var>param2[</var>, ..., <var>paramN</var>]]]) { + <var>statements</var> +}</pre> + +<h3 id="Parameters" name="Parameters">引数</h3> + +<dl> + <dt><code><var>name</var></code> {{optional_inline}}</dt> + <dd>関数名。省略可。省略した場合、関数は<em>無名関数</em>として認識されます。名前は関数本体のみにローカルです。</dd> + <dt><code><var>paramN</var></code><var> </var> {{optional_inline}}</dt> + <dd>関数に渡される引数の名前。関数は最大 255 の引数を持ち得ます。</dd> + <dt><code><var>statements</var></code></dt> + <dd>関数の本体を構成するステートメント。</dd> +</dl> + +<h2 id="Description" name="Description">解説</h2> + +<p><code>function*</code> 式は {{jsxref('Statements/function*', 'function* 文', "", 1)}}ととてもよく似ており、構文もほとんど同じです。<code>function*</code> 式と <code>function*</code> 文の主な違いは、<code>function*</code> 式で<em>無名</em>ジェネレーター関数を生成するには<em>関数名</em>が省略できる点です。詳細は {{jsxref("Functions", "functions")}} をご覧ください。</p> + +<h2 id="Examples" name="Examples">例</h2> + +<h3 id="Using_function*" name="Using_function*">function* を使用する</h3> + +<p>次の例では、無名ジェネレーター関数を定義し、<code>x</code> に割り当てます。関数は引数の二乗をもたらします:</p> + +<pre class="brush: js notranslate">let x = function*(y) { + yield y * y; +}; +</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-generator-function-definitions', 'function*')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">ブラウザーの互換性</h2> + +<div class="hidden">このページの互換性一覧表は構造化データから生成されています。データに協力していただけるのであれば、<a class="external" href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> をチェックアウトしてプルリクエストを送信してください。</div> + +<p>{{Compat("javascript.operators.function_star")}}</p> + +<h2 id="See_also" name="See_also">関連情報</h2> + +<ul> + <li>{{jsxref("Statements/function*", "function*")}} 文</li> + <li>{{jsxref("GeneratorFunction")}} オブジェクト</li> + <li><a href="/ja/docs/Web/JavaScript/Reference/Iteration_protocols">Iterator プロトコル</a></li> + <li>{{jsxref("Operators/yield", "yield")}}</li> + <li>{{jsxref("Operators/yield*", "yield*")}}</li> + <li>{{jsxref("Function")}} オブジェクト</li> + <li>{{jsxref("Statements/function", "function")}} 文</li> + <li>{{jsxref("Operators/function", "function")}} 式</li> + <li>{{jsxref("Functions_and_function_scope", "関数と関数スコープ", "", 1)}}</li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/generator_comprehensions/index.html b/files/ja/web/javascript/reference/operators/generator_comprehensions/index.html new file mode 100644 index 0000000000..250b8fad05 --- /dev/null +++ b/files/ja/web/javascript/reference/operators/generator_comprehensions/index.html @@ -0,0 +1,172 @@ +--- +title: ジェネレータ内包表記 +slug: Web/JavaScript/Reference/Operators/Generator_comprehensions +tags: + - Iterator + - JavaScript + - Non-standard + - Reference +translation_of: Archive/Web/JavaScript/Generator_comprehensions +--- +<div class="warning"><strong>非標準。使用しないでください!</strong><br> +ジェネレーター内包は非標準であり、Firefox 58 から削除されています。将来向きの用途には {{jsxref("Statements/function*", "ジェネレーター", "", 1)}} の使用を検討してください。</div> + +<div>{{jsSidebar("Operators")}}</div> + +<p><strong>generator comprehension</strong> 構文はすぐに既存の反復可能なオブジェクトに基づいて新たなジェネレーター関数を組み立てることができる JavaScript の式でした。しかし、これは標準仕様や Firefox の実装から削除されました。使用しないでください!</p> + +<h2 id="構文">構文</h2> + +<pre class="syntaxbox">(for (x of iterable) x) +(for (x of iterable) if (condition) x) +(for (x of iterable) for (y of iterable) x + y) +</pre> + +<h2 id="説明">説明</h2> + +<p>ジェネレータ内包表記の中では、この2種類のコンポーネントが許可されています。:</p> + +<ul> + <li>{{jsxref("Statements/for...of", "for...of")}}</li> + <li>{{jsxref("Statements/if...else", "if")}}</li> +</ul> + +<p><code>for-of</code>イテレーションは常に最初のコンポーネントです。複数の<code>for-of</code> イテレーションまたはif文が許可されています。</p> + +<p>{{jsxref("Operators/Array_comprehensions","配列内包","","true")}} の重大な欠点は、メモリー内に新しい配列全体を構築してしまうことです。配列内包への入力自体が小さい配列であるときのオーバーヘッドは小さいのですが、入力が大きな配列や処理の多い (あるいは本当に無限の) ジェネレーターであるときの配列の新規作成は問題になる場合があります。</p> + +<p>ジェネレーターはアイテムを必要なときに要求に応じて算出するため、一連のデータの計算処理を軽減します。ジェネレーター内包は構文的に、配列内包とほとんど同じです。こちらは中括弧の代わりに丸括弧を使用して、配列を構築する代わりに、すぐには実行されないジェネレーターを作成します。これらは、ジェネレーター作成を簡略化した構文と考えることができます。</p> + +<p>整数の大規模な数列に対して反復処理を行うイテレーター <code>it</code> を想定します。数列の値を 2 倍にする反復処理を行う、新たなイテレーターを作成したいとします。配列内包では、2 倍の値を含むのに十分な配列をメモリー内に作成します:</p> + +<pre class="brush: js">var doubles = [for (i in it) i * 2]; +</pre> + +<p>一方ジェネレーター内包は、必要なときに要求に応じて 2 倍の値を生成するイテレーターを作成します:</p> + +<pre class="brush: js">var it2 = (for (i in it) i * 2); +console.log(it2.next()); // The first value from it, doubled +console.log(it2.next()); // The second value from it, doubled +</pre> + +<p>ジェネレーター内包が関数の引数として使用されるときは、関数の呼び出しで使用される丸括弧によりジェネレーター内包の外側の丸括弧を省略できます:</p> + +<pre class="brush: js">var result = doSomething(for (i in it) i * 2); +</pre> + +<p>2 つの例の大きな違いは、ジェネレーター内包を使用すると 'obj' 構造を合計 1 回しかループする必要がないのと対照的に、配列内包ではイテレートの際に再びループすることです。</p> + +<h2 id="例">例</h2> + +<h3 id="簡単なジェネレータ内包表記">簡単なジェネレータ内包表記</h3> + +<pre class="brush:js">(for (i of [ 1, 2, 3 ]) i*i ); +// generator function which yields 1, 4, and 9 + +[...(for (i of [ 1, 2, 3 ]) i*i )]; +// [1, 4, 9] + +var abc = [ "A", "B", "C" ]; +(for (letters of abc) letters.toLowerCase()); +// generator function which yields "a", "b", and "c" +</pre> + +<h3 id="if文と用いたジェネレータ内包表記">if文と用いたジェネレータ内包表記</h3> + +<pre class="brush: js">var years = [ 1954, 1974, 1990, 2006, 2010, 2014 ]; + +(for (year of years) if (year > 2000) year); +// generator function which yields 2006, 2010, and 2014 + +(for (year of years) if (year > 2000) if(year < 2010) year); +// generator function which yields 2006, the same as below: + +(for (year of years) if (year > 2000 && year < 2010) year); +// generator function which yields 2006 +</pre> + +<h3 id="ジェネレータ関数と比較したジェネレータ内包表記">ジェネレータ関数と比較したジェネレータ内包表記</h3> + +<p>ジェネレータ内包表記構文を理解する簡単な方法はジェネレータ関数と比較することです。</p> + +<p>例 1: 簡単なジェネレータ</p> + +<pre class="brush: js">var numbers = [ 1, 2, 3 ]; + +// Generator function +(function*() { + for (let i of numbers) { + yield i * i; + } +})() + +// Generator comprehension +(for (i of numbers) i*i ); + +// Result: both return a generator which yields [ 1, 4, 9 ] +</pre> + +<p>例 2: ジェネレータ内で<code>if</code>を使用する</p> + +<pre class="brush: js">var numbers = [ 1, 2, 3 ]; + +// Generator function +(function*() { + for (let i of numbers) { + if (i < 3) { + yield i * 1; + } + } +})() + +// Generator comprehension +(for (i of numbers) if (i < 3) i); + +// Result: both return a generator which yields [ 1, 2 ]</pre> + +<h2 id="Specifications" name="Specifications">仕様</h2> + +<p>ジェネレーター内包は、ECMAScript 2015 で初期化されましたが、リビジョン 27 (2014 年 8 月) で取り除かれました。仕様セマンティクスについて、ES2015 の古いリビジョンをご覧ください。</p> + +<h2 id="Browser_compatibility" name="Browser_compatibility">ブラウザー実装状況</h2> + + + +<p>{{Compat("javascript.operators.generator_comprehensions")}}</p> + +<h2 id="Differences_to_the_older_JS1.7JS1.8_comprehensions" name="Differences_to_the_older_JS1.7JS1.8_comprehensions">古い JS1.7/JS1.8 の内包表記との違い</h2> + +<div class="warning">JS1.7/JS1.8 の内包表記は、バージョン 46 で削除しました ({{bug(1220564)}})。</div> + +<p><strong>古い内包表記の構文 (使用しないでください!):</strong></p> + +<pre class="brush: js example-bad">(X for (Y in Z)) +(X for each (Y in Z)) +(X for (Y of Z)) +</pre> + +<p>違い:</p> + +<ul> + <li>ESNext の内包表記は全体のかわりに"for"ノードごとに1スコープを生成します。 + <ul> + <li>旧: <code>[...(()=>x for (x of [0, 1, 2]))][1]() // 2</code></li> + <li>新: <code>[...(for (x of [0, 1, 2]) ()=>x)][1]() // 1, each iteration creates a fresh binding for x. </code></li> + </ul> + </li> + <li>ESNext の内包表記は代入式のかわりに"for"で始まります。 + <ul> + <li>旧: <code>(i * 2 for (i of numbers))</code></li> + <li>新: <code>(for (i of numbers) <code>i * 2</code>)</code></li> + </ul> + </li> + <li>ESNext の内包表記は複数の<code>if</code>と<code>for</code>コンポーネントを持ちます。</li> + <li>ESNext の内包表記は<code>{{jsxref("Statements/for...of", "for...of")}}</code>でのみ動作し、<code>{{jsxref("Statements/for...in", "for...in")}}</code>イテレーションでは動作しません。</li> +</ul> + +<h2 id="関連情報">関連情報</h2> + +<ul> + <li>{{jsxref("Statements/for...of", "for...of")}}</li> + <li>{{jsxref("Operators/Array_comprehensions", "Array comprehensions")}}</li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/greater_than/index.html b/files/ja/web/javascript/reference/operators/greater_than/index.html new file mode 100644 index 0000000000..247f76e0cb --- /dev/null +++ b/files/ja/web/javascript/reference/operators/greater_than/index.html @@ -0,0 +1,100 @@ +--- +title: 大なり (>) +slug: Web/JavaScript/Reference/Operators/Greater_than +tags: + - JavaScript + - Language feature + - Operator + - Reference +translation_of: Web/JavaScript/Reference/Operators/Greater_than +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>大なり演算子 (<code>></code>) は、左辺のオペランドが右辺のオペランドより大きい場合は <code>true</code> を返し、それ以外の場合は <code>false</code> を返します。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-greater-than.html")}}</div> + + + +<h2 id="構文">構文</h2> + +<pre class="syntaxbox notranslate">x > y</pre> + +<h2 id="解説">解説</h2> + +<p>オペランドは、 <a class="external external-icon" href="https://tc39.es/ecma262/#sec-abstract-relational-comparison" rel="noopener">抽象関係比較</a> アルゴリズムを使用して比較されます。このアルゴリズムの概要については、 <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Less_than">小なり</a> 演算子のドキュメントを参照して下さい。</p> + +<h2 id="例">例</h2> + +<h3 id="文字列と文字列の比較">文字列と文字列の比較</h3> + +<pre class="brush: js notranslate">console.log("a" > "b"); // false +console.log("a" > "a"); // false +console.log("a" > "3"); // true</pre> + +<h3 id="文字列と数値の比較">文字列と数値の比較</h3> + +<pre class="brush: js notranslate">console.log("5" > 3); // true +console.log("3" > 3); // false +console.log("3" > 5); // false + +console.log("hello" > 5); // false +console.log(5 > "hello"); // false + +console.log("5" > 3n); // true +console.log("3" > 5n); // false</pre> + +<h3 id="数値と数値の比較">数値と数値の比較</h3> + +<pre class="brush: js notranslate">console.log(5 > 3); // true +console.log(3 > 3); // false +console.log(3 > 5); // false</pre> + +<h3 id="数値と_BigInt_の比較">数値と BigInt の比較</h3> + +<pre class="brush: js notranslate">console.log(5n > 3); // true +console.log(3 > 5n); // false</pre> + +<h3 id="ブール値、_null_、_undefined_、_NaN_の比較">ブール値、 null 、 undefined 、 NaN の比較</h3> + +<pre class="brush: js notranslate">console.log(true > false); // true +console.log(false > true); // false + +console.log(true > 0); // true +console.log(true > 1); // false + +console.log(null > 0); // false +console.log(1 > null); // true + +console.log(undefined > 3); // false +console.log(3 > undefined); // false + +console.log(3 > NaN); // false +console.log(NaN > 3); // false</pre> + +<h2 id="仕様">仕様</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">仕様</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-relational-operators', 'Relational operators')}}</td> + </tr> + </tbody> +</table> + +<h2 id="ブラウザーの互換性">ブラウザーの互換性</h2> + + + +<p>{{Compat("javascript.operators.greater_than")}}</p> + +<h2 id="関連項目">関連項目</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Greater_than_or_equal">Greater than or equal operator</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Less_than">Less than operator</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Less_than_or_equal">Less than or equal operator</a></li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/greater_than_or_equal/index.html b/files/ja/web/javascript/reference/operators/greater_than_or_equal/index.html new file mode 100644 index 0000000000..b72d8cf06c --- /dev/null +++ b/files/ja/web/javascript/reference/operators/greater_than_or_equal/index.html @@ -0,0 +1,100 @@ +--- +title: 大なりイコール (>=) +slug: Web/JavaScript/Reference/Operators/Greater_than_or_equal +tags: + - JavaScript + - Language feature + - Operator + - Reference +translation_of: Web/JavaScript/Reference/Operators/Greater_than_or_equal +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>大なりイコール演算子 (<code>>=</code>) は、左辺のオペランドが右辺のオペランド以上の場合は <code>true</code> を返し、それ以外の場合は <code>false</code> を返します。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-greater-than-or-equal.html")}}</div> + + + +<h2 id="構文">構文</h2> + +<pre class="syntaxbox notranslate"> x >= y</pre> + +<h2 id="解説">解説</h2> + +<p>オペランドは、<a class="external external-icon" href="https://tc39.es/ecma262/#sec-abstract-relational-comparison" rel="noopener">抽象関係比較</a>アルゴリズムを使用して比較されます。 このアルゴリズムの概要は<a href="/en-US/docs/Web/JavaScript/Reference/Operators/Less_than">小なり</a>演算子のドキュメントを参照して下さい。</p> + +<h2 id="例">例</h2> + +<h3 id="文字列と文字列の比較">文字列と文字列の比較</h3> + +<pre class="brush: js notranslate">console.log("a" >= "b"); // false +console.log("a" >= "a"); // true +console.log("a" >= "3"); // true +</pre> + +<h3 id="文字列と数値の比較">文字列と数値の比較</h3> + +<pre class="brush: js notranslate">console.log("5" >= 3); // true +console.log("3" >= 3); // true +console.log("3" >= 5); // false + +console.log("hello" >= 5); // false +console.log(5 >= "hello"); // false</pre> + +<h3 id="数値と数値の比較">数値と数値の比較</h3> + +<pre class="brush: js notranslate">console.log(5 >= 3); // true +console.log(3 >= 3); // true +console.log(3 >= 5); // false</pre> + +<h3 id="数値と_BigInt_の比較">数値と BigInt の比較</h3> + +<pre class="brush: js notranslate">console.log(5n >= 3); // true +console.log(3 >= 3n); // true +console.log(3 >= 5n); // false</pre> + +<h3 id="ブール値、_null_、_undefined_、_NaN_の比較">ブール値、 null 、 undefined 、 NaN の比較</h3> + +<pre class="brush: js notranslate">console.log(true >= false); // true +console.log(true >= true); // true +console.log(false >= true); // false + +console.log(true >= 0); // true +console.log(true >= 1); // true + +console.log(null >= 0); // true +console.log(1 >= null); // true + +console.log(undefined >= 3); // false +console.log(3 >= undefined); // false + +console.log(3 >= NaN); // false +console.log(NaN >= 3); // false</pre> + +<h2 id="仕様">仕様</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">仕様</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-relational-operators', 'Relational operators')}}</td> + </tr> + </tbody> +</table> + +<h2 id="ブラウザーの互換性">ブラウザーの互換性</h2> + + + +<p>{{Compat("javascript.operators.greater_than_or_equal")}}</p> + +<h2 id="関連項目">関連項目</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Greater_than">Greater than operator</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Less_than">Less than operator</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Less_than_or_equal">Less than or equal operator</a></li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/grouping/index.html b/files/ja/web/javascript/reference/operators/grouping/index.html new file mode 100644 index 0000000000..6b2966037b --- /dev/null +++ b/files/ja/web/javascript/reference/operators/grouping/index.html @@ -0,0 +1,78 @@ +--- +title: グループ化演算子 +slug: Web/JavaScript/Reference/Operators/Grouping +tags: + - JavaScript + - Language feature + - Operator + - Primary Expressions + - 一次式 + - 演算子 + - 言語機能 +translation_of: Web/JavaScript/Reference/Operators/Grouping +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>グループ化演算子 <code>( )</code> は、式での評価の優先順位を制御します。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-groupingoperator.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"> ( )</pre> + +<h2 id="Description" name="Description">解説</h2> + +<p>グループ化演算子は、式または部分式の周りに括弧のペアで構成され、通常の<a href="/ja/docs/Web/JavaScript/Reference/Operators/Operator_Precedence">演算子の優先順位</a>を上書きし、より低い優先順位の式をより高い優先順位の式の前に評価できるようにします。その名の通り、括弧の中にあるものをグループ化します。</p> + +<h2 id="Examples" name="Examples">例</h2> + +<h3 id="Using_the_grouping_operator" name="Using_the_grouping_operator">グループ化演算子の使用</h3> + +<p>最初に乗算と除算をし、次に加算と引き算をする優先順位を、最初に加算を評価するように上書きします。</p> + +<pre class="brush:js">var a = 1; +var b = 2; +var c = 3; + +// default precedence +a + b * c // 7 +// evaluated by default like this +a + (b * c) // 7 + +// now overriding precedence +// addition before multiplication +(a + b) * c // 9 + +// which is equivalent to +a * c + b * c // 9 +</pre> + +<h2 id="Specifications" name="Specifications">仕様書</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">仕様書</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-grouping-operator', 'The Grouping Operator')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">ブラウザーの互換性</h2> + +<div class="hidden">このページの互換性一覧表は構造化データから生成されています。データに協力していただけるのであれば、 <a class="external" href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> をチェックアウトしてプルリクエストを送信してください。</div> + +<p>{{Compat("javascript.operators.grouping")}}</p> + +<h2 id="See_also" name="See_also">関連情報</h2> + +<ul> + <li><a href="/ja/docs/Web/JavaScript/Reference/Operators/Operator_Precedence">演算子の優先順位</a></li> + <li>{{jsxref("Operators/delete", "delete")}}</li> + <li>{{jsxref("Operators/typeof", "typeof")}}</li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/in/index.html b/files/ja/web/javascript/reference/operators/in/index.html new file mode 100644 index 0000000000..ac6c61dc62 --- /dev/null +++ b/files/ja/web/javascript/reference/operators/in/index.html @@ -0,0 +1,141 @@ +--- +title: in +slug: Web/JavaScript/Reference/Operators/in +tags: + - JavaScript + - Language feature + - Operator + - Relational Operators +translation_of: Web/JavaScript/Reference/Operators/in +--- +<div>{{jsSidebar("Operators")}}</div> + +<p><strong><code>in</code> 演算子</strong>は、指定されたプロパティが指定されたオブジェクトにある場合に <code>true</code> を返します。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-inoperator.html")}}</div> + + + +<h2 id="Syntax" name="Syntax">構文</h2> + +<pre class="syntaxbox notranslate"><var>prop</var> in <var>object</var></pre> + +<h3 id="Parameters" name="Parameters">引数</h3> + +<dl> + <dt><code><var>prop</var></code></dt> + <dd>プロパティ名または配列のインデックスを表す文字列式またはシンボルです(シンボルではない場合は、文字列に強制変換されます)。</dd> +</dl> + +<dl> + <dt><code><var>object</var></code></dt> + <dd>オブジェクト(またはそのプロトタイプチェーン)に、指定された名前(<code><var>prop</var></code>)のプロパティが含まれているかどうかを確認するオブジェクト。</dd> +</dl> + +<h2 id="Examples" name="Examples">例</h2> + +<h3 id="Basic_usage" name="Basic_usage">基本的な使い方</h3> + +<p>次の例で <code>in</code> 演算子の使用法を示します。</p> + +<pre class="brush:js notranslate">// Arrays +let trees = ['redwood', 'bay', 'cedar', 'oak', 'maple']; +0 in trees // true を返す +3 in trees // true を返す +6 in trees // false を返す +'bay' in trees // false を返す (インデックスの指す値ではなく、インデックスの数字を指定しなければならない) +'length' in trees // true を返す (length は Array のプロパティ) +Symbol.iterator in trees // true を返す (配列は反復可能。ES2015 以上で動作する) + +// 定義済みオブジェクト +'PI' in Math // true を返す + +// ユーザー定義オブジェクト +let mycar = {make: 'Honda', model: 'Accord', year: 1998}; +'make' in mycar // true を返す +'model' in mycar // true を返す +</pre> + +<p><code>in</code> 演算子の右側には、オブジェクトを指定しなければなりません。例えば、<code>String</code> コンストラクタで作成した文字列は指定できますが、文字列リテラルは指定できません。</p> + +<pre class="brush:js notranslate">let color1 = new String('green'); +'length' in color1 // true を返す + +let color2 = 'coral'; +// エラーが発生 (color2 は String オブジェクトではありません) +'length' in color2 +</pre> + +<h3 id="Using_in_with_deleted_or_undefined_properties" name="Using_in_with_deleted_or_undefined_properties">削除済みあるいは未定義状態のプロパティへの <code>in</code> の使用</h3> + +<p><code><a href="/ja/docs/JavaScript/Reference/Operators/delete" title="JavaScript/Reference/Operators/Special/delete">delete</a></code> 演算子で削除されたプロパティについて、<code>in</code> 演算子は <code>false</code> を返します。</p> + +<pre class="brush:js notranslate">let mycar = {make: 'Honda', model: 'Accord', year: 1998}; +delete mycar.make; +'make' in mycar; // false を返す + +let trees = new Array('redwood', 'bay', 'cedar', 'oak', 'maple'); +delete trees[3]; +3 in trees; // false を返す +</pre> + +<p>{{jsxref("Global_Objects/undefined", "undefined")}} を設定しているが削除されていないプロパティについて、<code>in</code> 演算子は true を返します。</p> + +<pre class="brush:js notranslate">let mycar = {make: 'Honda', model: 'Accord', year: 1998}; +mycar.make = undefined; +'make' in mycar; // true を返す +</pre> + +<pre class="brush:js notranslate">let trees = new Array('redwood', 'bay', 'cedar', 'oak', 'maple'); +trees[3] = undefined; +3 in trees; // true を返す +</pre> + +<p><code>in</code> 演算子は、空の配列スロットに対して <code>false</code> を返します。直接アクセスしても <code>undefined</code> が返されます。</p> + +<pre class="brush:js notranslate">let empties = new Array(3) +empties[2] // undefined を返す +2 in empties // false を返す +</pre> + +<p>これを避けるためには、新しい配列が常に空でない値で埋められるようにするか、配列の終わりを超えてインデックスに書き込まないようにします。</p> + +<pre class="brush:js notranslate">let empties = new Array(3).fill(undefined) +2 in empties // true を返す +</pre> + +<h3 id="Inherited_properties" name="Inherited_properties">継承されたプロパティ</h3> + +<p><code>in</code> 演算子は、プロトタイプチェーンのプロパティに対して <code>true</code> を返します。(<em>継承されていない</em>プロパティのみをチェックする場合は、代わりに {{jsxref("Object.prototype.hasOwnProperty()")}} を使用してください)。</p> + +<pre class="brush:js notranslate">'toString' in {} // returns true +</pre> + +<h2 id="Specifications" name="Specifications">仕様</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">仕様書</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-relational-operators', 'Relational Operators')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">ブラウザー実装状況</h2> + + + +<p>{{Compat("javascript.operators.in")}}</p> + +<h2 id="See_also" name="See_also">関連情報</h2> + +<ul> + <li><code><a href="/ja/docs/Web/JavaScript/Reference/Statements/for...in">for...in</a></code></li> + <li><code><a href="/ja/docs/Web/JavaScript/Reference/Operators/delete">delete</a></code></li> + <li>{{jsxref("Object.prototype.hasOwnProperty()")}}</li> + <li>{{jsxref("Reflect.has()")}}</li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Enumerability_and_ownership_of_properties">プロパティの列挙可能性と所有権</a></li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/increment/index.html b/files/ja/web/javascript/reference/operators/increment/index.html new file mode 100644 index 0000000000..9b575490f5 --- /dev/null +++ b/files/ja/web/javascript/reference/operators/increment/index.html @@ -0,0 +1,81 @@ +--- +title: インクリメント (++) +slug: Web/JavaScript/Reference/Operators/Increment +tags: + - JavaScript + - Language feature + - Operator + - Reference +translation_of: Web/JavaScript/Reference/Operators/Increment +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>インクリメント演算子 (<code>++</code>) は、オペランドをインクリメント (1を加算) して値を返します。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-increment.html")}}</div> + + + +<h2 id="構文">構文</h2> + +<pre class="syntaxbox notranslate"><strong>Operator:</strong> <var>x</var>++ or ++<var>x</var> +</pre> + +<h2 id="解説">解説</h2> + +<p>オペランドに後置で演算子を付けると (例えば、 <code><var>x</var>++</code>) 、インクリメント演算子はインクリメントしますが、インクリメント前の値を返します。</p> + +<p>オペランドに前置で演算子を付けると (例えば、 <code>++<var>x</var></code>) 、インクリメント演算子はインクリメントし、インクリメント後の値を返します。</p> + +<h2 id="例">例</h2> + +<h3 id="後置インクリメント">後置インクリメント</h3> + +<pre class="brush: js notranslate">let x = 3; +y = x++; + +// y = 3 +// x = 4 +</pre> + +<h3 id="前置インクリメント">前置インクリメント</h3> + +<pre class="brush: js notranslate">let a = 2; +b = ++a; + +// a = 3 +// b = 3 +</pre> + +<h2 id="仕様">仕様</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">仕様</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-postfix-increment-operator', 'Increment operator')}}</td> + </tr> + </tbody> +</table> + +<h2 id="ブラウザーの互換性">ブラウザーの互換性</h2> + + + +<p>{{Compat("javascript.operators.increment")}}</p> + +<h2 id="関連項目">関連項目</h2> + +<ul> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Addition">加算演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Subtraction">減算演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Multiplication">乗算演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Division">除算演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Remainder">剰余演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Exponentiation">べき乗演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Decrement">デクリメント演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Unary_negation">単項マイナス演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Unary_plus">単項プラス演算子</a></li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/index.html b/files/ja/web/javascript/reference/operators/index.html new file mode 100644 index 0000000000..71489adc52 --- /dev/null +++ b/files/ja/web/javascript/reference/operators/index.html @@ -0,0 +1,299 @@ +--- +title: 式と演算子 +slug: Web/JavaScript/Reference/Operators +tags: + - JavaScript + - Landing page + - Operators + - Overview + - Reference + - 概要 + - 演算子 +translation_of: Web/JavaScript/Reference/Operators +--- +<div>{{JSSidebar("Operators")}}</div> + +<p class="summary">この節では、JavaScript 言語のすべての演算子、式、キーワードについて記述しています。</p> + +<h2 id="Expressions_and_operators_by_category" name="Expressions_and_operators_by_category">式と演算子 (カテゴリ別)</h2> + +<p>アルファベット順リストは左側のサイドバーをご覧ください。</p> + +<h3 id="Primary_expressions" name="Primary_expressions">基本式</h3> + +<p>JavaScript の基本的なキーワードと一般的な式です。</p> + +<dl> + <dt>{{JSxRef("Operators/this", "this")}}</dt> + <dd><code>this</code> キーワードは関数の実行コンテキストを参照します。</dd> + <dt>{{JSxRef("Operators/function", "function")}}</dt> + <dd><code>function</code> キーワードは関数式を定義します。</dd> + <dt>{{JSxRef("Operators/class", "class")}}</dt> + <dd><code>class</code> キーワードはクラス式を定義します。</dd> + <dt>{{JSxRef("Operators/function*", "function*")}}</dt> + <dd><code>function*</code> キーワードはジェネレーター関数式を定義します。</dd> + <dt>{{JSxRef("Operators/yield", "yield")}}</dt> + <dd>ジェネレーター関数の一時停止と再開を行います。</dd> + <dt>{{JSxRef("Operators/yield*", "yield*")}}</dt> + <dd>別のジェネレーター関数または反復可能オブジェクトを代行します。</dd> + <dt>{{JSxRef("Operators/async_function", "async function")}}</dt> + <dd><code>async function</code> は非同期の関数式を定義します。</dd> + <dt>{{JSxRef("Operators/await", "await")}}</dt> + <dd>非同期関数式の停止/再開と、プロミスの解決/拒絶を待ちます。</dd> + <dt>{{JSxRef("Global_Objects/Array", "[]")}}</dt> + <dd>配列初期化子またはリテラル構文です。</dd> + <dt>{{JSxRef("Operators/Object_initializer", "{}")}}</dt> + <dd>オブジェクト初期化子またはリテラル構文です。</dd> + <dt>{{JSxRef("Global_Objects/RegExp", "/ab+c/i")}}</dt> + <dd>正規表現式のリテラル構文です。</dd> + <dt>{{JSxRef("Operators/Grouping", "( )")}}</dt> + <dd>グループ化演算子です。</dd> +</dl> + +<h3 id="Left-hand-side_expressions" name="Left-hand-side_expressions">左辺式</h3> + +<p>左辺値は、代入の対象になります。</p> + +<dl> + <dt>{{JSxRef("Operators/Property_accessors", "プロパティアクセサー", "", 1)}}</dt> + <dd>プロパティアクセス演算子はオブジェクトのプロパティやメソッドへのアクセスを提供します<br> + (<code>object.property</code> や <code>object["property"]</code>)。</dd> + <dt>{{JSxRef("Operators/new", "new")}}</dt> + <dd><code>new</code> 演算子はコンストラクタのインスタンスを作成します。</dd> + <dt>{{JSxRef("Operators/new%2Etarget", "new.target")}}</dt> + <dd>コンストラクタ内で <code>new.target</code> を使うことで、{{jsxref("Operators/new", "new")}} によって呼び出されるコンストラクタを参照できます。</dd> + <dt>{{JSxRef("Operators/super", "super")}}</dt> + <dd><code>super</code> キーワードは親コンストラクタを呼び出します。</dd> + <dt>{{JSxRef("Operators/Spread_syntax", "...obj")}}</dt> + <dd>展開記法 (スプレッド記法) は、式を複数の引数または複数の要素に展開して、それぞれ関数呼び出しまたは配列リテラルに渡します。</dd> +</dl> + +<h3 id="Increment_and_decrement" name="Increment_and_decrement">インクリメントとデクリメント</h3> + +<p>接尾/接頭辞のインクリメント演算子と接尾/接頭辞のデクリメント演算子です。</p> + +<dl> + <dt>{{JSxRef("Operators/Increment", "A++")}}</dt> + <dd>後置型インクリメント演算子。</dd> + <dt>{{JSxRef("Operators/Decrement", "A--")}}</dt> + <dd>後置型デクリメント演算子。</dd> + <dt>{{JSxRef("Operators/Increment", "++A")}}</dt> + <dd>前置型インクリメント演算子。</dd> + <dt>{{JSxRef("Operators/Decrement", "--A")}}</dt> + <dd>前置型デクリメント演算子。</dd> +</dl> + +<h3 id="Unary_operators" name="Unary_operators">単項演算子</h3> + +<p>単項演算は、1 個のオペランドによる演算です。</p> + +<dl> + <dt>{{JSxRef("Operators/delete", "delete")}}</dt> + <dd><code>delete</code> 演算子は、オブジェクトからプロパティを削除します。</dd> + <dt>{{JSxRef("Operators/void", "void")}}</dt> + <dd><code>void</code> 演算子は、式の戻り値を破棄します。</dd> + <dt>{{JSxRef("Operators/typeof", "typeof")}}</dt> + <dd><code>typeof</code> 演算子は、与えられたオブジェクトの型を判別します。</dd> + <dt>{{JSxRef("Operators/Unary_plus", "+")}}</dt> + <dd>単項正値演算子は、そのオペランドを Number 型に変換します。</dd> + <dt>{{JSxRef("Operators/Unary_negation", "-")}}</dt> + <dd>単項負値演算子は、そのオペランドを Number 型に変換して正負を反転します。</dd> + <dt>{{JSxRef("Operators/Bitwise_NOT", "~")}}</dt> + <dd>ビット否定演算子です。</dd> + <dt>{{JSxRef("Operators/Logical_NOT", "!")}}</dt> + <dd>論理否定演算子です。</dd> +</dl> + +<h3 id="Arithmetic_operators" name="Arithmetic_operators">算術演算子</h3> + +<p>算術演算子は、数値 (リテラルまたは値) をオペランドとして取り、1 個の数値を返します。</p> + +<dl> + <dt>{{JSxRef("Operators/Addition", "+")}}</dt> + <dd>加算演算子です。</dd> + <dt>{{JSxRef("Operators/Subtraction", "-")}}</dt> + <dd>減算演算子です。</dd> + <dt>{{JSxRef("Operators/Division", "/")}}</dt> + <dd>除算演算子です。</dd> + <dt>{{JSxRef("Operators/Multiplication", "*")}}</dt> + <dd>乗算演算子です。</dd> + <dt>{{JSxRef("Operators/Remainder", "%")}}</dt> + <dd>剰余演算子です。</dd> + <dt>{{JSxRef("Operators/Exponentiation", "**")}}</dt> + <dd>べき乗演算子です。</dd> +</dl> + +<h3 id="Relational_operators" name="Relational_operators">関係演算子</h3> + +<p>比較演算子は、そのオペランドを比較し、その比較が真かどうかに基づいて <code>Boolean</code> 値を返します。</p> + +<dl> + <dt>{{JSxRef("Operators/in", "in")}}</dt> + <dd><code>in</code> 演算子は、与えられたプロパティをオブジェクトが持っているかどうかを判別します。</dd> + <dt>{{JSxRef("Operators/instanceof", "instanceof")}}</dt> + <dd><code>instanceof</code> 演算子は、オブジェクトが別のオブジェクトのインスタンスかどうかを判別します。</dd> + <dt>{{JSxRef("Operators/Less_than", "<")}}</dt> + <dd>小なり演算子です。</dd> + <dt>{{JSxRef("Operators/Greater_than", ">")}}</dt> + <dd>大なり演算子です。</dd> + <dt>{{JSxRef("Operators/Less_than_or_equal", "<=")}}</dt> + <dd>小なりイコール演算子です。</dd> + <dt>{{JSxRef("Operators/Greater_than_or_equal", ">=")}}</dt> + <dd>大なりイコール演算子です。</dd> +</dl> + +<div class="note"> +<p><strong>注: =></strong> は演算子ではなく、<a href="/ja/docs/Web/JavaScript/Reference/Functions/Arrow_functions">アロー関数</a> のための記法です。</p> +</div> + +<h3 id="Equality_operators" name="Equality_operators">等値演算子</h3> + +<p>等値演算子の評価結果は常に、比較が真かどうかに基づいて <code>Boolean</code> 型の値になります。</p> + +<dl> + <dt>{{JSxRef("Operators/Equality", "==")}}</dt> + <dd>等値演算子です。</dd> + <dt>{{JSxRef("Operators/Inequality", "!=")}}</dt> + <dd>不等値演算子です。</dd> + <dt>{{JSxRef("Operators/Strict_equality", "===")}}</dt> + <dd>同値演算子です。</dd> + <dt>{{JSxRef("Operators/Strict_inequality", "!==")}}</dt> + <dd>非同値演算子です。</dd> +</dl> + +<h3 id="Bitwise_shift_operators" name="Bitwise_shift_operators">ビットシフト演算子</h3> + +<p>オペランドのすべてのビットをシフト演算します。</p> + +<dl> + <dt>{{JSxRef("Operators/Left_shift", "<<")}}</dt> + <dd>ビット左シフト演算子です。</dd> + <dt>{{JSxRef("Operators/Right_shift", ">>")}}</dt> + <dd>ビット右シフト演算子です。</dd> + <dt>{{JSxRef("Operators/Unsigned_right_shift", ">>>")}}</dt> + <dd>ビット符号なし右シフト演算子です。</dd> +</dl> + +<h3 id="Binary_bitwise_operators" name="Binary_bitwise_operators">バイナリービット演算子</h3> + +<p>ビット演算子は、そのオペランドを 32 ビット (0 と 1) の並びとして扱い、標準の JavaScript 数値を返します。</p> + +<dl> + <dt>{{JSxRef("Operators/Bitwise_AND", "&")}}</dt> + <dd>ビット論理積 (AND) です。</dd> + <dt>{{JSxRef("Operators/Bitwise_OR", "|")}}</dt> + <dd>ビット論理和 (OR) です。</dd> + <dt>{{JSxRef("Operators/Bitwise_XOR", "^")}}</dt> + <dd>ビット排他的論理和 (XOR) です。</dd> +</dl> + +<h3 id="Binary_logical_operators" name="Binary_logical_operators">バイナリー論理演算子</h3> + +<p>論理演算には、一般的に (論理) 真偽値が使用され、それが置かれた時に真偽値を返します。</p> + +<dl> + <dt>{{JSxRef("Operators/Logical_AND", "&&")}}</dt> + <dd>論理積 (AND) です。</dd> + <dt>{{JSxRef("Operators/Logical_OR", "||")}}</dt> + <dd>論理和 (OR) です。</dd> + <dt>{{JSxRef("Operators/Nullish_coalescing_operator", "??")}}</dt> + <dd>Null 合体 です。</dd> +</dl> + + + +<h3 id="Conditional_ternary_operator" name="Conditional_ternary_operator">条件 (三項) 演算子</h3> + +<dl> + <dt>{{JSxRef("Operators/Conditional_Operator", "(condition ? ifTrue : ifFalse)")}}</dt> + <dd> + <p>この条件演算子は、条件の論理値を基に、2 つの値のいずれか一方を返します。</p> + </dd> +</dl> + +<h3 id="Optional_Chaining_operator" name="Optional_Chaining_operator">オプショナルチェイニング演算子</h3> + +<dl> + <dt>{{JSxRef("Operators/Optional_chaining", "?.")}}</dt> + <dd> + <p>オプショナルチェイニング演算子は、参照が <a href="/ja/docs/Glossary/nullish">nullish</a>(<a href="/ja/docs/Web/JavaScript/Reference/Global_Objects/null"><code>null</code></a> または <a href="/ja/docs/Web/JavaScript/Reference/Global_Objects/undefined"><code>undefined</code></a>)の場合にエラーを発生させるのではなく、<code>undefined</code> を返します。</p> + </dd> +</dl> + +<h3 id="Assignment_operators" name="Assignment_operators">代入演算子</h3> + +<p>代入演算子は、右辺のオペランドに基づいて、値を左辺のオペランドに代入します。</p> + +<dl> + <dt>{{JSxRef("Operators/Assignment", "=")}}</dt> + <dd>代入演算子です。</dd> + <dt>{{JSxRef("Operators/Multiplication_assignment", "*=")}}</dt> + <dd>乗算値を代入します。</dd> + <dt>{{JSxRef("Operators/Exponentiation_assignment", "**=")}}</dt> + <dd>べき乗値を代入します。</dd> + <dt>{{JSxRef("Operators/Division_assignment", "/=")}}</dt> + <dd>除算値を代入します。</dd> + <dt>{{JSxRef("Operators/Remainder_assignment", "%=")}}</dt> + <dd>剰余値を代入します。</dd> + <dt>{{JSxRef("Operators/Addition_assignment", "+=")}}</dt> + <dd>加算値を代入します。</dd> + <dt>{{JSxRef("Operators/Subtraction_assignment", "-=")}}</dt> + <dd>減算値を代入します。</dd> + <dt>{{JSxRef("Operators/Left_shift_assignment", "<<=")}}</dt> + <dd>左シフトした値を代入します。</dd> + <dt>{{JSxRef("Operators/Right_shift_assignment", ">>=")}}</dt> + <dd>右シフトした値を代入します。</dd> + <dt>{{JSxRef("Operators/Unsigned_right_shift_assignment", ">>>=")}}</dt> + <dd>符号なしの右シフトした値を代入します。</dd> + <dt>{{JSxRef("Operators/Bitwise_AND_assignment", "&=")}}</dt> + <dd>ビット論理積 (AND) の値を代入します。</dd> + <dt>{{JSxRef("Operators/Bitwise_XOR_assignment", "^=")}}</dt> + <dd>ビット排他的論理和 (XOR) の値を代入します。</dd> + <dt>{{JSxRef("Operators/Bitwise_OR_assignment", "|=")}}</dt> + <dd>ビット論理和 (OR) の値を代入します。</dd> + <dt>{{JSxRef("Operators/Logical_AND_assignment", "&&=")}}</dt> + <dd>論理積代入です。</dd> + <dt>{{JSxRef("Operators/Logical_OR_assignment", "||=")}}</dt> + <dd>論理和代入です。</dd> + <dt>{{JSxRef("Operators/Logical_nullish_assignment", "??=")}}</dt> + <dd>論理 Null 代入です。</dd> + <dt>{{JSxRef("Operators/Destructuring_assignment", "[a, b] = [1, 2]")}}<br> + {{JSxRef("Operators/Destructuring_assignment", "{a, b} = {a:1, b:2}")}}</dt> + <dd> + <p>分割代入は、配列やオブジェクトのプロパティを、配列やオブジェクトリテラルに似た構文を使用して変数に代入します。</p> + </dd> +</dl> + +<h3 id="Comma_operator" name="Comma_operator">カンマ演算子</h3> + +<dl> + <dt>{{JSxRef("Operators/Comma_Operator", ",")}}</dt> + <dd>カンマ演算子は、複数の式を単一の文で評価し、その最後の式の結果を返します。</dd> +</dl> + +<h2 id="Specifications" name="Specifications">仕様</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">仕様書</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-ecmascript-language-expressions', 'ECMAScript Language: Expressions')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">ブラウザーの互換性</h2> + +<div class="hidden">このページの互換性一覧表は構造化データから生成されています。データに協力していただけるのであれば、<a class="external" href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> をチェックアウトしてプルリクエストを送信してください。</div> + +<p>{{Compat("javascript.operators")}}</p> + +<h2 id="See_also" name="See_also">関連情報</h2> + +<ul> + <li><a href="/ja/docs/Web/JavaScript/Reference/Operators/Operator_Precedence">演算子の優先順位</a></li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/inequality/index.html b/files/ja/web/javascript/reference/operators/inequality/index.html new file mode 100644 index 0000000000..7dba373779 --- /dev/null +++ b/files/ja/web/javascript/reference/operators/inequality/index.html @@ -0,0 +1,98 @@ +--- +title: 不等価 (!=) +slug: Web/JavaScript/Reference/Operators/Inequality +tags: + - JavaScript + - Language feature + - Operator + - Reference +translation_of: Web/JavaScript/Reference/Operators/Inequality +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>不等価演算子 (<code>!=</code>) は、2つのオペランドが等しくないかをチェックし、ブール値の結果を返します。<a href="/en-US/docs/Web/JavaScript/Reference/Operators/Strict_inequality">厳密不等価</a>演算子とは異なり、異なる型のオペランドを変換して比較を行おうとします。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-inequality.html")}}</div> + + + +<h2 id="構文">構文</h2> + +<pre class="syntaxbox notranslate">x != y</pre> + +<h2 id="説明">説明</h2> + +<p>不等価演算子は、そのオペランドが等しくないかどうかをチェックします。これは<a href="/en-US/docs/Web/JavaScript/Reference/Operators/Equality">等価</a>演算子の否定なので、次の2行は常に同じ結果になります。</p> + +<pre class="brush: js notranslate">x != y + +!(x == y)</pre> + +<p>比較アルゴリズムの詳細については、<a href="/en-US/docs/Web/JavaScript/Reference/Operators/Equality">等価</a>演算子のページを参照して下さい。</p> + +<p>等価演算子と同様に、不等価演算子は異なる型のオペランドを変換して比較しようとします。</p> + +<pre class="brush: js notranslate">3 != "3"; // false</pre> + +<p>これを防止し、異なる型が異なる結果を返すようにするには、代わりに<a href="/en-US/docs/Web/JavaScript/Reference/Operators/Strict_inequality">厳密不等価</a>演算子を使用します:</p> + +<pre class="brush: js notranslate">3 !== "3"; // true</pre> + +<h2 id="例">例</h2> + +<h3 id="型変換なしの比較">型変換なしの比較</h3> + +<pre class="brush: js notranslate">1 != 2; // true +"hello" != "hola"; // true + +1 != 1; // false +"hello" != "hello"; // false</pre> + +<h3 id="型変換ありの比較">型変換ありの比較</h3> + +<pre class="brush: js notranslate">"1" != 1; // false +1 != "1"; // false +0 != false; // false +0 != null; // true +0 != undefined; // true +null != undefined; // false + +const number1 = new Number(3); +const number2 = new Number(3); +number1 != 3; // false +number1 != number2; // true</pre> + +<h3 id="オブジェクトの比較">オブジェクトの比較</h3> + +<pre class="brush: js notranslate">const object1 = {"key": "value"} +const object2 = {"key": "value"}; + +object1 != object2 // true +object2 != object2 // false</pre> + +<h2 id="仕様">仕様</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">仕様</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-equality-operators', 'Equality operators')}}</td> + </tr> + </tbody> +</table> + +<h2 id="ブラウザー実装状況">ブラウザー実装状況</h2> + + + +<p>{{Compat("javascript.operators.inequality")}}</p> + +<h2 id="関連項目">関連項目</h2> + +<ul> + <li><a href="/docs/Web/JavaScript/Reference/Operators/Equality">等価演算子</a></li> + <li><a href="/docs/Web/JavaScript/Reference/Operators/Strict_equality">厳密等価演算子</a></li> + <li><a href="/docs/Web/JavaScript/Reference/Operators/Strict_inequality">厳密不等価演算子</a></li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/instanceof/index.html b/files/ja/web/javascript/reference/operators/instanceof/index.html new file mode 100644 index 0000000000..a238d8b522 --- /dev/null +++ b/files/ja/web/javascript/reference/operators/instanceof/index.html @@ -0,0 +1,175 @@ +--- +title: instanceof +slug: Web/JavaScript/Reference/Operators/instanceof +tags: + - JavaScript + - Language feature + - Object + - Operator + - Prototype + - Relational Operators + - instanceof +translation_of: Web/JavaScript/Reference/Operators/instanceof +--- +<div>{{jsSidebar("Operators")}}</div> + +<p><strong><code>instanceof</code></strong> 演算子は、オブジェクトが自身のプロトタイプにコンストラクタの <code>prototype</code> プロパティを持っているかを確認します。戻り値はブール値です。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-instanceof.html")}}</div> + + + +<h2 id="Syntax" name="Syntax">構文</h2> + +<pre class="syntaxbox notranslate"><var>object</var> instanceof <var>constructor</var></pre> + +<h3 id="Parameters" name="Parameters">引数</h3> + +<dl> + <dt><code><var>object</var></code></dt> + <dd>確認するオブジェクト</dd> +</dl> + +<dl> + <dt><code><var>constructor</var></code></dt> + <dd>オブジェクトに対して確認を行う関数</dd> +</dl> + +<h2 id="説明">説明</h2> + +<p><code>instanceof</code> 演算子は、<code>object</code> のプロトタイプチェインで <code>constructor.prototype</code> の存在を確認します。</p> + +<pre class="brush: js notranslate">// コンストラクタを定義 +function C() {} +function D() {} + +let o = new C() + +// true なぜなら: Object.getPrototypeOf(o) === C.prototype +o instanceof C; + +// false D.prototype は o のプロトタイプチェーンのどこにも存在しない +o instanceof D; + +o instanceof Object; // true なぜなら... +C.prototype instanceof Object // true だから + +C.prototype = {} +let o2 = new C() + +o2 instanceof C; // true + +// false C.prototype は o のプロトタイプチェーンの +// どこにも存在しない +o instanceof C; + +D.prototype = new C(); // 継承を使用 +let o3 = new D() +o3 instanceof D; // true +o3 instanceof C; // true o3 のプロトタイプチェーンに C.prototype があるため。 +</pre> + +<p>注意事項: <code>instanceof</code> による確認結果はコンストラクタの <code>prototype</code> プロパティの変化に従って変わることがあります。また、オブジェクトのプロトタイプを <code>Object.setPrototypeOf</code> を用いて変更した場合や、非標準の <code>__proto__</code> 疑似プロパティを用いた場合も変わりえます。</p> + +<h3 id="instanceof_and_multiple_context_e.g._frames_or_windows" name="instanceof_and_multiple_context_e.g._frames_or_windows"><code>instanceof</code> と複数のコンテキスト (例: frame や window)</h3> + +<p>異なるスコープは、別々の実行環境を持ちます。つまり、それらは別々の組み込み物 (別々のグローバルオブジェクト、別々のコンストラクタ 等々) を持ちます。これにより予期せぬ結果になる場合があります。例えば、<code>[] instanceof window.frames[0].Array</code> は、<code>Array.prototype !== window.frames[0].Array</code> であることおよび配列が以前から継承していることから <code>false</code> を返します。</p> + +<p>これは、始めはわかりにくいかもしれませんが、スクリプトで複数のフレームやウィンドウを扱い始め、オブジェクトをあるコンテキストから別のコンテキストへ関数を経由して渡すようになると、正当かつ重要な事項になります。例えば、<code>Array.isArray(<var>myObj</var>)</code> を使用して、与えられたオブジェクトが実際に配列であるかどうかを安全にチェックできます。</p> + +<p>例えば、別のコンテキストで <a href="/ja/docs/Web/API/Node">Nodes</a> が <a href="/ja/docs/Web/API/SVGElement">SVGElement</a> であるかどうかをチェックするには、<code>myNode instanceof myNode.ownerDocument.defaultView.SVGElement</code> を使用します。</p> + +<div class="note"> +<p><strong>Mozilla 開発者への注意点</strong></p> + +<p>XPCOM を用いるコードでは <code>instanceof</code> に特別な効果があります: <code>obj instanceof <em>xpcomInterface</em></code> (例えば <code>Components.interfaces.nsIFile</code>) は <code>obj.QueryInterface(<em>xpcomInterface</em>)</code> を呼び出し、<code>QueryInterface</code> が成功した場合に <code>true</code> を返します。</p> + +<p>このような呼び出しの副作用として、<code>instanceof</code> による確認の成功後に <code><var>obj</var></code> の <code>xpcomInterface</code> のプロパティを利用できることがあります。標準 JavaScript の環境と異なり、<code>obj</code> が異なるスコープ由来であっても <code><var>obj</var> instanceof <var>xpcomInterface</var></code> での確認は期待どおりに動作します。</p> +</div> + +<h2 id="Examples" name="Examples">例</h2> + +<h3 id="Demonstrating_that_String_and_Date_are_of_type_Object_and_exceptional_cases" name="Demonstrating_that_String_and_Date_are_of_type_Object_and_exceptional_cases"><code>String</code> や <code>Date</code> が <code>Object</code> タイプであることの実証</h3> + +<p>以下のコードは、<code>String</code> や <code>Date</code> オブジェクトが <code>Object</code> タイプでもある (<code>Object</code> から派生している) ことの実証に <code>instanceof</code> を用いています。</p> + +<p>また、オブジェクトリテラルを用いて作成されたオブジェクトに対する例外、つまり、prototype が <code>undefined</code> であるにも関わらず <code>instanceof Object</code> が <code>true</code> を報告する例を示します。</p> + +<pre class="brush: js notranslate">let simpleStr = 'This is a simple string' +let myString = new String() +let newStr = new String('コンストラクターで作成された文字列') +let myDate = new Date() +let myObj = {} +let myNonObj = Object.create(null) + +simpleStr instanceof String // false を返す 文字列リテラルはオブジェクトではありません。 +myString instanceof String // true を返す +newStr instanceof String // true を返す +myString instanceof Object // true を返す + +myObj instanceof Object // true を返す すべてのオブジェクトリテラルはプロトタイプとして Object.prototype を持っています。 +({}) instanceof Object // true を返す 上記と同じ +myNonObj instanceof Object // false を返す プロトタイプはプロトタイプチェーンの終わりです(null) +myString instanceof Date // false を返す + +myDate instanceof Date // true を返す +myDate instanceof Object // true を返す +myDate instanceof String // false を返す +</pre> + +<h3 id="Demonstrating_that_mycar_is_of_type_Car_and_type_Object" name="Demonstrating_that_mycar_is_of_type_Car_and_type_Object"><code>mycar</code> が <code>Car</code> タイプおよび <code>Object</code> タイプであることの実証</h3> + +<p>以下のコードは、<code>Car</code> オブジェクトタイプとそのインスタンスである <code>mycar</code> を生成しています。<code>instanceof</code> 演算子で、<code>mycar</code> は <code>Car</code> タイプおよび <code>Object</code> タイプであることを実証します。</p> + +<pre class="brush: js notranslate">function Car(make, model, year) { + this.make = make; + this.model = model; + this.year = year; +} +let mycar = new Car('Honda', 'Accord', 1998) +let a = mycar instanceof Car // true を返す +let b = mycar instanceof Object // true を返す +</pre> + +<h3 id="Not_an_instanceof" name="Not_an_instanceof">インスタンスではないことの実証</h3> + +<p>オブジェクトが特定のコンストラクタの <code>instanceof</code> でないかどうかを確認するには次のようにします。</p> + +<pre class="brush: js notranslate">if (!(mycar instanceof Car)) { + // Do something, like: + // mycar = new Car(mycar) +} +</pre> + +<p>これは実際には次のものとは異なります。</p> + +<pre class="brush: js notranslate">if (!mycar instanceof Car)</pre> + +<p>これは常に <code>false</code> になります。(<code>!mycar</code> は <code>instanceof</code> の前に評価され、常に <code>Car</code> のインスタンスを確認したブール値になります)。</p> + +<h2 id="Specifications" name="Specifications">仕様</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">仕様書</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-relational-operators', 'Relational Operators')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">ブラウザー実装状況</h2> + + + +<p>{{Compat("javascript.operators.instanceof")}}</p> + +<h2 id="See_also" name="See_also">関連情報</h2> + +<ul> + <li><code><a href="/ja/docs/Web/JavaScript/Reference/Operators/typeof" title="/ja/docs/JavaScript/Reference/Operators/typeof">typeof</a></code></li> + <li>{{jsxref("Symbol.hasInstance")}}</li> + <li>{{jsxref("Object.prototype.isPrototypeOf")}}</li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/left_shift/index.html b/files/ja/web/javascript/reference/operators/left_shift/index.html new file mode 100644 index 0000000000..9a274f84b2 --- /dev/null +++ b/files/ja/web/javascript/reference/operators/left_shift/index.html @@ -0,0 +1,77 @@ +--- +title: 左シフト (<<) +slug: Web/JavaScript/Reference/Operators/Left_shift +tags: + - Bitwise operator + - JavaScript + - Language feature + - Operator + - Reference + - ビット演算子 + - 演算子 + - 言語機能 +translation_of: Web/JavaScript/Reference/Operators/Left_shift +--- +<div>{{jsSidebar("Operators")}}</div> + +<p><strong>左シフト演算子 (<code><<</code>)</strong>は、1つ目のオペランドを指定されたビット数だけ左にずらします。左にずらしてあふれたビットは廃棄されます。0のビットが右からずれて入ります。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-left-shift.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"><code><var>a</var> << <var>b</var></code> +</pre> + +<h2 id="Description" name="Description">解説</h2> + +<p>この演算子は、1つ目のオペランドを指定されたビット数だけ左にずらします。左にずらしてあふれたビットは廃棄されます。0のビットが右からずれて入ります。</p> + +<p>例えば <code>9 << 2</code> は 36 になります。</p> + +<pre class="brush: js notranslate">. 9 (10進数): 00000000000000000000000000001001 (2進数) + -------------------------------- +9 << 2 (10進数): 00000000000000000000000000100100 (2進数) = 36 (10進数) +</pre> + +<p>任意の数 <code>x</code> を <code>y</code> ビット分だけ左にビット単位にずらすと、 <code>x * 2 ** y</code> になります。<br> + ですから、例えば <code>9 << 3</code> は <code>9 * (2 ** 3) = 9 * (8) = 72</code> になります。</p> + +<h2 id="Examples" name="Examples">例</h2> + +<h3 id="Using_left_shift" name="Using_left_shift">左シフトの使用</h3> + +<pre class="brush: js notranslate">9 << 3; // 72 + +// 9 * (2 ** 3) = 9 * (8) = 72 +</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-bitwise-shift-operators', 'Bitwise Shift Operators')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">ブラウザーの互換性</h2> + +<div class="hidden">このページの互換性一覧表は構造化データから生成されています。データに協力していただけるのであれば、 <a class="external" href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> をチェックアウトしてプルリクエストを送信してください。</div> + +<p>{{Compat("javascript.operators.left_shift")}}</p> + +<h2 id="See_also" name="See_also">関連情報</h2> + +<ul> + <li><a href="/ja/docs/Web/JavaScript/Guide/Expressions_and_Operators#Bitwise">JavaScript ガイドのビット毎演算子</a></li> + <li><a href="/ja/docs/Web/JavaScript/Reference/Operators/Left_shift_assignment">左シフト代入演算子</a></li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/left_shift_assignment/index.html b/files/ja/web/javascript/reference/operators/left_shift_assignment/index.html new file mode 100644 index 0000000000..cbe638ccd2 --- /dev/null +++ b/files/ja/web/javascript/reference/operators/left_shift_assignment/index.html @@ -0,0 +1,61 @@ +--- +title: 左シフト代入 (<<=) +slug: Web/JavaScript/Reference/Operators/Left_shift_assignment +tags: + - Assignment operator + - JavaScript + - Language feature + - Operator + - Reference +translation_of: Web/JavaScript/Reference/Operators/Left_shift_assignment +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>左シフト代入演算子 (<code><<=</code>) は、指定された量のビットを左に移動し、結果を変数に代入します。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-left-shift-assignment.html")}}</div> + +<div></div> + + + +<h2 id="構文">構文</h2> + +<pre class="syntaxbox notranslate"><strong>Operator:</strong> x <<= y +<strong>Meaning:</strong> x = x << y</pre> + +<h2 id="例">例</h2> + +<h3 id="左シフト代入の使用">左シフト代入の使用</h3> + +<pre class="brush: js notranslate">let a = 5; +// 00000000000000000000000000000101 + +bar <<= 2; // 20 +// 00000000000000000000000000010100</pre> + +<h2 id="仕様">仕様</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">仕様</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-assignment-operators', 'Assignment operators')}}</td> + </tr> + </tbody> +</table> + +<h2 id="ブラウザー実装状況">ブラウザー実装状況</h2> + + + +<p>{{Compat("javascript.operators.left_shift_assignment")}}</p> + +<h2 id="関連項目">関連項目</h2> + +<ul> + <li><a href="/docs/Web/JavaScript/Guide/Expressions_and_Operators#Assignment">代入演算子</a></li> + <li><a href="/docs/Web/JavaScript/Reference/Operators/Left_shift">左シフト演算子</a></li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/less_than/index.html b/files/ja/web/javascript/reference/operators/less_than/index.html new file mode 100644 index 0000000000..c684188b51 --- /dev/null +++ b/files/ja/web/javascript/reference/operators/less_than/index.html @@ -0,0 +1,115 @@ +--- +title: 小なり (<) +slug: Web/JavaScript/Reference/Operators/Less_than +tags: + - JavaScript + - Language feature + - Operator + - Reference +translation_of: Web/JavaScript/Reference/Operators/Less_than +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>小なり演算子 (<code><</code>) は、左辺のオペランドが右辺のオペランドより小さい場合は <code>true</code> を返し、それ以外の場合は <code>false</code> を返します。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-less-than.html")}}</div> + + + +<h2 id="構文">構文</h2> + +<pre class="syntaxbox notranslate"> x < y</pre> + +<h2 id="説明">説明</h2> + +<p>オペランドは、以下に大まかに要約されている<a href="https://tc39.es/ecma262/#sec-abstract-relational-comparison">抽象関係比較</a>アルゴリズムを使用して比較されます:</p> + +<ul> + <li>最初に、オブジェクトは <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toPrimitive">Symbol.ToPrimitive</a></code> を使用してプリミティブに変換されます。</li> + <li>両方の値が文字列である場合、それらに含まれる Unicode コードポイントの値に基づいて、文字列として比較されます。</li> + <li>それ以外の場合、 JavaScript は非数値型を数値に変換しようとします: + <ul> + <li>ブール値 <code>true</code> および <code>false</code> は、それぞれ 1 および 0 に変換されます。</li> + <li><code>null</code> は 0 に変換されます。</li> + <li><code>undefined</code> は <code>NaN</code> に変換されます。</li> + <li>文字列は、含まれている値に基づいて変換され、数値が含まれていない場合は <code>NaN</code> として変換されます。</li> + </ul> + </li> + <li>いずれかの値が <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN">NaN</a></code> の場合、演算子は <code>false</code> を返します。</li> + <li>それ以外の場合、値は数値として比較されます。</li> +</ul> + +<h2 id="例">例</h2> + +<h3 id="文字列と文字列の比較">文字列と文字列の比較</h3> + +<pre class="brush: js notranslate">console.log("a" < "b"); // true +console.log("a" < "a"); // false +console.log("a" < "3"); // false</pre> + +<h3 id="文字列と数値の比較">文字列と数値の比較</h3> + +<pre class="brush: js notranslate">console.log("5" < 3); // false +console.log("3" < 3); // false +console.log("3" < 5); // true + +console.log("hello" < 5); // false +console.log(5 < "hello"); // false + +console.log("5" < 3n); // false +console.log("3" < 5n); // true</pre> + +<h3 id="数値と数値の比較">数値と数値の比較</h3> + +<pre class="brush: js notranslate">console.log(5 < 3); // false +console.log(3 < 3); // false +console.log(3 < 5); // true</pre> + +<h3 id="数値と_BigInt_の比較">数値と BigInt の比較</h3> + +<pre class="brush: js notranslate">console.log(5n < 3); // false +console.log(3 < 5n); // true</pre> + +<h3 id="ブール値_null_undefined_NaN_の比較">ブール値, null, undefined, NaN の比較</h3> + +<pre class="brush: js notranslate">console.log(true < false); // false +console.log(false < true); // true + +console.log(0 < true); // true +console.log(true < 1); // false + +console.log(null < 0); // false +console.log(null < 1); // true + +console.log(undefined < 3); // false +console.log(3 < undefined); // false + +console.log(3 < NaN); // false +console.log(NaN < 3); // false</pre> + +<h2 id="仕様">仕様</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">仕様</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-relational-operators', 'Relational operators')}}</td> + </tr> + </tbody> +</table> + +<h2 id="ブラウザー実装状況">ブラウザー実装状況</h2> + + + +<p>{{Compat("javascript.operators.less_than")}}</p> + +<h2 id="関連項目">関連項目</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Greater_than">Greater than operator</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Greater_than_or_equal">Greater than or equal operator</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Less_than_or_equal">Less than or equal operator</a></li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/less_than_or_equal/index.html b/files/ja/web/javascript/reference/operators/less_than_or_equal/index.html new file mode 100644 index 0000000000..425fe7c264 --- /dev/null +++ b/files/ja/web/javascript/reference/operators/less_than_or_equal/index.html @@ -0,0 +1,104 @@ +--- +title: 小なりイコール (<=) +slug: Web/JavaScript/Reference/Operators/Less_than_or_equal +tags: + - JavaScript + - Language feature + - Operator + - Reference + - 演算子 + - 言語機能 +translation_of: Web/JavaScript/Reference/Operators/Less_than_or_equal +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>小なりイコール演算子 (<code><=</code>) は、左のオペランドが右のオペランドより小さいか等しい場合に <code>true</code> を返し、それ以外の場合は <code>false</code> を返します。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-less-than-or-equal.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"> x <= y</pre> + +<h2 id="Description" name="Description">解説</h2> + +<p>オペランドは<a class="external external-icon" href="https://tc39.es/ecma262/#sec-abstract-relational-comparison" rel="noopener">抽象関係比較</a>アルゴリズムを使用して比較されます。このアルゴリズムの概要は<a href="/ja/docs/Web/JavaScript/Reference/Operators/Greater_than">大なり</a>演算子のドキュメントをご覧ください。</p> + +<h2 id="Examples" name="Examples">例</h2> + +<h3 id="String_to_string_comparison" name="String_to_string_comparison">文字列と文字列の比較</h3> + +<pre class="brush: js notranslate">console.log("a" <= "b"); // true +console.log("a" <= "a"); // true +console.log("a" <= "3"); // false +</pre> + +<h3 id="String_to_number_comparison" name="String_to_number_comparison">文字列と数値の比較</h3> + +<pre class="brush: js notranslate">console.log("5" <= 3); // false +console.log("3" <= 3); // true +console.log("3" <= 5); // true + +console.log("hello" <= 5); // false +console.log(5 <= "hello"); // false</pre> + +<h3 id="Number_to_Number_comparison" name="Number_to_Number_comparison">数値と数値の比較</h3> + +<pre class="brush: js notranslate">console.log(5 <= 3); // false +console.log(3 <= 3); // true +console.log(3 <= 5); // true</pre> + +<h3 id="Number_to_BigInt_comparison" name="Number_to_BigInt_comparison">数値と BigInt の比較</h3> + +<pre class="brush: js notranslate">console.log(5n <= 3); // false +console.log(3 <= 3n); // true +console.log(3 <= 5n); // true</pre> + +<h3 id="Comparing_Boolean_null_undefined_NaN" name="Comparing_Boolean_null_undefined_NaN">論理型, null, undefined, NaN の比較</h3> + +<pre class="brush: js notranslate">console.log(true <= false); // false +console.log(true <= true); // true +console.log(false <= true); // true + +console.log(true <= 0); // false +console.log(true <= 1); // true + +console.log(null <= 0); // true +console.log(1 <= null); // false + +console.log(undefined <= 3); // false +console.log(3 <= undefined); // false + +console.log(3 <= NaN); // false +console.log(NaN <= 3); // false</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-relational-operators', 'Relational operators')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">ブラウザーの互換性</h2> + +<div class="hidden">このページの互換性一覧表は構造化データから生成されています。データに協力していただけるのであれば、 <a class="external" href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> をチェックアウトしてプルリクエストを送信してください。</div> + +<p>{{Compat("javascript.operators.less_than_or_equal")}}</p> + +<h2 id="See_also" name="See_also">関連情報</h2> + +<ul> + <li><a href="/ja/docs/Web/JavaScript/Reference/Operators/Greater_than">大なり演算子</a></li> + <li><a href="/ja/docs/Web/JavaScript/Reference/Operators/Greater_than_or_equal">大なりイコール演算子</a></li> + <li><a href="/ja/docs/Web/JavaScript/Reference/Operators/Less_than">小なり演算子</a></li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/logical_and/index.html b/files/ja/web/javascript/reference/operators/logical_and/index.html new file mode 100644 index 0000000000..467230cfec --- /dev/null +++ b/files/ja/web/javascript/reference/operators/logical_and/index.html @@ -0,0 +1,146 @@ +--- +title: 論理積 (&&) +slug: Web/JavaScript/Reference/Operators/Logical_AND +tags: + - JavaScript + - Language feature + - Logical Operator + - Operator + - Reference + - 演算子 + - 言語機能 + - 論理演算子 +translation_of: Web/JavaScript/Reference/Operators/Logical_AND +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>論理積 (<code>&&</code>) 演算子 (論理結合) をオペランドの組み合わせに対して使用すると、すべてのオペランドが true である場合に true になります。一般的には {{jsxref("Boolean")}} (論理) 値で使用されます。その場合は論理値を返します。ただし <code>&&</code> 演算子は実際には指定されたオペランドのうち一つの値を返すので、この演算子が論理値以外で使用された場合は、論理値以外の値を返すことになります。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-logical-and.html", "shorter")}}</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"><em>expr1</em> && <em>expr2</em> +</pre> + +<h2 id="Description" name="Description">解説</h2> + +<p><code>expr<strong>1</strong></code> が <code>true</code> に変換できる場合は <code>expr<strong>2</strong></code> を返し、それ以外の場合は <code>expr<strong>1</strong></code> を返します。</p> + +<p>ある値が <code>true</code> に変換できる場合、その値は真値 ({{Glossary("truthy")}}) と呼ばれます。ある値が <code>false</code> に変換できる場合、その値は偽値 ({{Glossary("falsy")}}) と呼ばれます。</p> + +<p>false に変換することができる式の例を示します。</p> + +<ul> + <li><code>null</code></li> + <li><code>NaN</code></li> + <li><code>0</code></li> + <li>空文字列 (<code>""</code> または <code>''</code> または <code>``</code>)</li> + <li><code>undefined</code></li> +</ul> + +<p><code>&&</code> 演算子では論理値以外のオペランドを使用することができますが、返値が常に <a href="/ja/docs/Web/JavaScript/Data_structures#Boolean_type">boolean プリミティブ</a>に変換することが可能であるため、論理演算子と見なすことができます。返値 (または一般的な式) を対応する論理値に明示的に変換するには、二重の<a href="/ja/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Logical_NOT">否定演算子</a>または {{jsxref("Global_Objects/Boolean/Boolean", "Boolean")}} コンストラクターを使用してください。</p> + +<h3 id="Short-circuit_evaluation" name="Short-circuit_evaluation">短絡評価</h3> + +<p>論理積の式は左から右へと評価され、下記の規則を使用して「短絡」評価が可能なように評価されます。</p> + +<p><code>(偽値の式) && <em>expr</em></code> は短絡評価で偽値の式に評価されます。</p> + +<p>短絡とは、上記の <code><em>expr</em></code> の部分が<strong>評価されず</strong>、したがって、これを行うことの副作用が効果を及ぼさないことを意味します (例えば、 <code><em>expr</em></code> が関数呼び出しであった場合、この場所では呼び出されません)。これは、最初のオペランドが評価された時点で、すでに演算子の値が決定しているためです。例を示します。</p> + +<pre class="brush: js notranslate">function A(){ console.log('called A'); return false; } +function B(){ console.log('called B'); return true; } + +console.log( A() && B() ); +// 関数呼び出しによって "called A" がログ出力され、 +// それから false (演算子の結果の値) が出力されます。 +</pre> + +<h3 id="Operator_precedence" name="Operator_precedence">演算子の優先順位</h3> + +<p>以下の式は同じであるように見えるかもしれませんが、異なります。 <code>&&</code> 演算子は <code>||</code> 演算子よりも先に実行されるからです (<a href="/ja/docs/Web/JavaScript/Reference/Operators/Operator_Precedence">演算子の優先順位</a>を参照)。</p> + +<pre class="brush: js notranslate">true || false && false // true を返す。 && が先に実行されるため +(true || false) && false // false を返す。演算子の優先順位が適用されないため</pre> + +<h2 id="Examples" name="Examples">例</h2> + +<h3 id="Using_AND" name="Using_AND">論理和の使用</h3> + +<p>以下のコードは <code>&&</code> (論理積) 演算子の例を示しています。</p> + +<pre class="brush: js notranslate">a1 = true && true // t && t returns true +a2 = true && false // t && f returns false +a3 = false && true // f && t returns false +a4 = false && (3 == 4) // f && f returns false +a5 = 'Cat' && 'Dog' // t && t returns "Dog" +a6 = false && 'Cat' // f && t returns false +a7 = 'Cat' && false // t && f returns false +a8 = '' && false // f && f returns "" +a9 = false && '' // f && f returns false</pre> + +<h3 id="Conversion_rules_for_booleans" name="Conversion_rules_for_booleans">論理型の変換規則</h3> + +<h4 id="AND_から_OR_への変換">AND から OR への変換</h4> + +<p><strong>論理型</strong>に関する以下の操作は、</p> + +<pre class="brush: js notranslate">bCondition1 && bCondition2</pre> + +<p>常に以下のものと等しくなります。</p> + +<pre class="brush: js notranslate">!(!bCondition1 || !bCondition2)</pre> + +<h4 id="Converting_OR_to_AND" name="Converting_OR_to_AND">OR から AND への変換</h4> + +<p><strong>論理型</strong>に関する以下の操作は、</p> + +<pre class="brush: js notranslate">bCondition1 || bCondition2</pre> + +<p>常に以下のものと等しくなります。</p> + +<pre class="brush: js notranslate">!(!bCondition1 && !bCondition2)</pre> + +<h3 id="Removing_nested_parentheses" name="Removing_nested_parentheses">入れ子になった括弧の除去</h3> + +<p>論理式は左から右に評価されるので、いくつかのルールに従って複雑な式から括弧を削除することは常に可能です。</p> + +<p>以下の<strong>論理型</strong>に関する複合操作は、</p> + +<pre class="brush: js notranslate">bCondition1 || (bCondition2 && bCondition3)</pre> + +<p>常に以下のものと等しくなります。</p> + +<pre class="brush: js notranslate">bCondition1 || bCondition2 && bCondition3</pre> + +<h2 id="Specifications" name="Specifications">仕様書</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">仕様書</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#prod-LogicalANDExpression', 'Logical AND expression')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">ブラウザーの互換性</h2> + +<div class="hidden">このページの互換性一覧表は構造化データから生成されています。データに協力していただけるのであれば、 <a class="external" href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> をチェックアウトしてプルリクエストを送信してください。</div> + +<p>{{Compat("javascript.operators.logical_and")}}</p> + +<h2 id="See_also" name="See_also">関連情報</h2> + +<ul> + <li>{{jsxref("Boolean")}}</li> + <li>{{Glossary("Truthy")}}</li> + <li>{{Glossary("Falsy")}}</li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/logical_and_assignment/index.html b/files/ja/web/javascript/reference/operators/logical_and_assignment/index.html new file mode 100644 index 0000000000..1e74fc6b2d --- /dev/null +++ b/files/ja/web/javascript/reference/operators/logical_and_assignment/index.html @@ -0,0 +1,89 @@ +--- +title: 論理積代入 (&&=) +slug: Web/JavaScript/Reference/Operators/Logical_AND_assignment +tags: + - JavaScript + - Language feature + - Logical assignment + - Operator + - Reference +translation_of: Web/JavaScript/Reference/Operators/Logical_AND_assignment +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>論理積代入 (<code>x &&= y</code>) 演算子は、<code>x</code> が {{Glossary("truthy")}} である場合にのみ代入します。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-logical-and-assignment.html")}}</div> + +<div class="hidden">The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> and send us a pull request.</div> + +<h2 id="構文">構文</h2> + +<pre class="syntaxbox notranslate"><em>expr1</em> &&= <em>expr2</em> +</pre> + +<h2 id="説明">説明</h2> + +<h3 id="短絡評価(ショートサーキット)">短絡評価(ショートサーキット)</h3> + +<p><a href="/docs/Web/JavaScript/Reference/Operators/Logical_AND">論理積演算子</a>は左から右に評価され、次のルールを使って短絡評価の可能性があるかどうかテストされます。</p> + +<p><code>(偽値の式) && expr</code> は、偽値の式が短絡評価されます。</p> + +<p>短絡評価とは、上記の <code><em>expr</em></code> 部分が<strong>評価されない</strong>ことを意味します。したがって、評価された場合の副作用は発生しません。(例えば、<code><em>expr</em></code> が関数呼び出しである場合、呼び出しは行われません。)</p> + +<p>論理積代入も短絡評価されます。これは、<code>x &&= y</code> が以下と等価であることを意味します。</p> + +<pre class="brush: js notranslate">x && (x = y);</pre> + +<p>そして、常に代入が行われる以下と等価ではありません。</p> + +<pre class="brush: js notranslate example-bad">x = x && y; +</pre> + +<h2 id="例">例</h2> + +<h3 id="論理積代入演算子の使用">論理積代入演算子の使用</h3> + +<pre class="brush: js notranslate">let x = 0; +let y = 1; + +x &&= 0; // 0 +x &&= 1; // 0 +y &&= 1; // 1 +y &&= 0; // 0 +</pre> + +<h2 id="仕様">仕様</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">仕様書</th> + </tr> + </thead> + <tbody> + <tr> + </tr> + <tr> + <td>{{SpecName('Logical Assignment', '#sec-assignment-operators', 'Assignment operators')}}</td> + </tr> + </tbody> +</table> + +<h2 id="ブラウザの互換性">ブラウザの互換性</h2> + + + +<p>{{Compat("javascript.operators.logical_and_assignment")}}</p> + +<h2 id="関連情報">関連情報</h2> + +<ul> + <li><a href="/ja/docs/Web/JavaScript/Reference/Operators/Logical_AND">論理積 (&&)</a></li> + <li><a href="/ja/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator">Null合体 (<code>??</code>)</a></li> + <li><a href="/ja/docs/Web/JavaScript/Reference/Operators/Bitwise_AND_assignment">ビット論理積代入 (<code>&=</code>)</a></li> + <li>{{jsxref("Boolean")}}</li> + <li>{{Glossary("Truthy")}}</li> + <li>{{Glossary("Falsy")}}</li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/logical_not/index.html b/files/ja/web/javascript/reference/operators/logical_not/index.html new file mode 100644 index 0000000000..9ba7180d85 --- /dev/null +++ b/files/ja/web/javascript/reference/operators/logical_not/index.html @@ -0,0 +1,109 @@ +--- +title: 論理否定 (!) +slug: Web/JavaScript/Reference/Operators/Logical_NOT +tags: + - JavaScript + - Language feature + - Logical Operator + - Operator + - Reference + - 演算子 + - 言語機能 + - 論理演算子 +translation_of: Web/JavaScript/Reference/Operators/Logical_NOT +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>論理否定 (<code>!</code>) 演算子 (論理反転、否定) は、真値を取ると偽値になり、その逆も同様です。これは通常 {{jsxref("Boolean")}} (論理型) の値に使用されます。論理型以外の値に使用した場合、単一のオペランドが <code>true</code> に変換できる場合は <code>false</code> を返し、それ以外は <code>true</code> を返します。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-logical-not.html", "shorter")}}</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>expr</var> +</pre> + +<h2 id="Description" name="Description">解説</h2> + +<p>単一のオペランドが <code>true</code> に変換できる場合は <code>false</code> を返し、それ以外は <code>true</code> を返します。</p> + +<p>ある値が <code>true</code> に変換できる場合、その値は真値 ({{Glossary("truthy")}}) と呼ばれます。ある値が <code>false</code> に変換できる場合、その値は偽値 ({{Glossary("falsy")}}) と呼ばれます。</p> + +<p>false に変換することができる式の例を示します。</p> + +<ul> + <li><code>null</code></li> + <li><code>NaN</code></li> + <li><code>0</code></li> + <li>空文字列 (<code>""</code> または <code>''</code> または <code>``</code>)</li> + <li><code>undefined</code></li> +</ul> + +<p><code>!</code> 演算子は論理値以外のオペランドに対して使用することができますが、返値が常に <a href="/ja/docs/Web/JavaScript/Data_structures#Boolean_type">boolean プリミティブ</a>に変換することが可能であるため、論理演算子と見なすことができます。返値 (または一般的な式) を対応する論理値に明示的に変換するには、二重の<a href="/ja/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Logical_NOT">否定演算子</a>または {{jsxref("Global_Objects/Boolean/Boolean", "Boolean")}} コンストラクターを使用してください。</p> + +<h2 id="Examples" name="Examples">例</h2> + +<h3 id="Using_NOT" name="Using_NOT">否定の使用</h3> + +<p>以下のコードは <code>!</code> (論理否定) 演算子の例を示しています。</p> + +<pre class="brush: js notranslate">n1 = !true // !t returns false +n2 = !false // !f returns true +n3 = !'' // !f returns true +n4 = !'Cat' // !t returns false</pre> + +<h3 id="Double_NOT_!!" name="Double_NOT_!!">二重否定 (<code>!!</code>)</h3> + +<p>複数の否定演算子を連続して使用することで、明示的にあらゆる値を対応する<a href="/ja/docs/Web/JavaScript/Data_structures#Boolean_type">論理型プリミティブ</a>に変換することができます。変換は値の「真値性」または「偽値性」に基づいて行われます ({{Glossary("truthy")}} および {{Glossary("falsy")}} を参照)。</p> + +<p>同じ変換は {{jsxref("Global_Objects/Boolean/Boolean", "Boolean")}} 関数を通じて行うこともできます。</p> + +<pre class="brush: js notranslate">n1 = !!true // !!truthy returns true +n2 = !!{} // !!truthy returns true: <strong>any</strong> object is truthy... +n3 = !!(new Boolean(false)) // ...even Boolean objects with a false <em>.valueOf()</em>! +n4 = !!false // !!falsy returns false +n5 = !!"" // !!falsy returns false +n6 = !!Boolean(false) // !!falsy returns false</pre> + +<h3 id="Converting_between_NOTs" name="Converting_between_NOTs">否定同士の変換</h3> + +<p>以下の操作を<strong>論理値</strong>で行った場合、</p> + +<pre class="brush: js notranslate">!!bCondition</pre> + +<p>常に以下のものと等しくなります。</p> + +<pre class="brush: js notranslate">bCondition</pre> + +<h2 id="Specifications" name="Specifications">仕様書</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">仕様書</th> + </tr> + </thead> + <tbody> + <tr> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#prod-LogicalORExpression', 'Logical OR expression')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">ブラウザーの互換性</h2> + +<div class="hidden">このページの互換性一覧表は構造化データから生成されています。データに協力していただけるのであれば、 <a class="external" href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> をチェックアウトしてプルリクエストを送信してください。</div> + +<p>{{Compat("javascript.operators.logical_or")}}</p> + +<h2 id="See_also" name="See_also">関連情報</h2> + +<ul> + <li>{{jsxref("Boolean")}}</li> + <li>{{Glossary("Truthy")}}</li> + <li>{{Glossary("Falsy")}}</li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/logical_nullish_assignment/index.html b/files/ja/web/javascript/reference/operators/logical_nullish_assignment/index.html new file mode 100644 index 0000000000..1c2235a65e --- /dev/null +++ b/files/ja/web/javascript/reference/operators/logical_nullish_assignment/index.html @@ -0,0 +1,89 @@ +--- +title: Null 合体代入 (??=) +slug: Web/JavaScript/Reference/Operators/Logical_nullish_assignment +tags: + - Assignment operator + - JavaScript + - Language feature + - Logical Operator + - Operator + - Reference +translation_of: Web/JavaScript/Reference/Operators/Logical_nullish_assignment +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>Null 合体代入 (<code>x ??= y</code>) 演算子は、<code>x</code> が {{Glossary("nullish")}} (<code>null</code> または <code>undefined</code>) である場合にのみ代入を行います。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-logical-nullish-assignment.html")}}</div> + +<div class="hidden">The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> and send us a pull request.</div> + +<h2 id="構文">構文</h2> + +<pre class="syntaxbox notranslate"><em>expr1</em> ??= <em>expr2</em> +</pre> + +<h2 id="説明">説明</h2> + +<h3 id="短絡評価(ショートサーキット)">短絡評価(ショートサーキット)</h3> + +<p><a href="/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator">Null 合体演算子</a>は左から右に評価され、次のルールを使って短絡評価の可能性があるかどうかテストされます。</p> + +<p><code>(null や undefined ではない式) ?? expr</code> は、左辺が <code>null</code> でも <code>undefined</code> でもないことが証明されたら、左辺の式が短絡評価されます。</p> + +<p>短絡評価とは、上記の <code><em>expr</em></code> 部分が<strong>評価されない</strong>ことを意味します。したがって、評価された場合の副作用は発生しません。(例えば、<code><em>expr</em></code> が関数呼び出しである場合、呼び出しは行われません。)</p> + +<p>Null 合体代入も短絡評価されます。これは、<code>x ??= y</code> が以下と等価であることを意味します。</p> + +<pre class="brush: js notranslate">x ?? (x = y);</pre> + +<p>そして、常に代入が行われる以下と等価ではありません。</p> + +<pre class="brush: js notranslate example-bad">x = x ?? y; +</pre> + +<h2 id="例">例</h2> + +<h3 id="Null_合体代入演算子の使用">Null 合体代入演算子の使用</h3> + +<pre class="brush: js notranslate">function config(options) { + options.duration ??= 100; + options.speed ??= 25; + return options; +} + +config({ duration: 125 }); // { duration: 125, speed: 25 } +config({}); // { duration: 100, speed: 25 } +</pre> + +<h2 id="仕様">仕様</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">仕様書</th> + </tr> + </thead> + <tbody> + <tr> + </tr> + <tr> + <td>{{SpecName('Logical Assignment', '#sec-assignment-operators', 'Assignment operators')}}</td> + </tr> + </tbody> +</table> + +<h2 id="ブラウザの互換性">ブラウザの互換性</h2> + + + +<p>{{Compat("javascript.operators.logical_nullish_assignment")}}</p> + +<h2 id="関連情報">関連情報</h2> + +<ul> + <li><a href="/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator">Null 合体演算子 (<code>??</code>)</a></li> + <li>{{Glossary("Nullish")}}</li> + <li>{{Glossary("Truthy")}}</li> + <li>{{Glossary("Falsy")}}</li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/logical_operators/index.html b/files/ja/web/javascript/reference/operators/logical_operators/index.html new file mode 100644 index 0000000000..5b2cf76b3a --- /dev/null +++ b/files/ja/web/javascript/reference/operators/logical_operators/index.html @@ -0,0 +1,294 @@ +--- +title: 論理演算子 +slug: Web/JavaScript/Reference/Operators/Logical_Operators +tags: + - JavaScript + - Operator +translation_of: Web/JavaScript/Reference/Operators +--- +<div>{{jsSidebar("Operators")}}</div> + +<h2 id=".E6.A6.82.E8.A6.81" name=".E6.A6.82.E8.A6.81">概要</h2> + +<p>{{ 原語併記("論理演算子", "Logical operators") }} は、基本的に真偽(論理)値とともに用いられ真偽値を返します。しかし、<code>&&</code> および <code>||</code> 演算子は真偽値ではない値も使うことができるため、その場合は、真偽値ではない値を返すことがあります。その場合の考え方は以下の「説明」の欄の記載の通りとなります。</p> + +<h2 id="Description" name="Description">説明</h2> + +<p>論理演算子を以下の表で説明します。:</p> + +<table class="fullwidth-table"> + <tbody> + <tr> + <th>演算子</th> + <th>使用法</th> + <th>説明</th> + </tr> + <tr> + <td>論理 AND(<code>&&</code>)</td> + <td><code><em>expr1</em> && <em>expr2</em></code></td> + <td><code>expr1</code> を false と見ることができる場合は、<code>expr1</code> を返します。そうでない場合は、<code>expr2</code> を返します。したがって、真偽値と共に使われた場合、 演算対象の両方が true ならば、<code>&&</code> は、true を返し、そうでなければ、false を返します。</td> + </tr> + <tr> + <td>論理 OR (<code>||</code>)</td> + <td><code><em>expr1</em> || <em>expr2</em></code></td> + <td><code>expr1</code> を true と見ることができる場合は、<code>expr1</code> を返します。そうでない場合は、<code>expr2</code> を返します。したがって、真偽値と共に使われた場合、 演算対象のどちらかが true ならば、<code>||</code> は、true を返し、両方とも false の場合は、false を返します。</td> + </tr> + <tr> + <td>論理 NOT (<code>!</code>)</td> + <td><code>!<em>expr</em></code></td> + <td>単一の演算対象が true と見ることができる場合は、false を返します。そうでない場合は、true を返します。</td> + </tr> + </tbody> +</table> + +<p><code>true</code> に変換できる値は、いわゆる {{Glossary("truthy")}} です。<code>false</code> に変換できる値は、いわゆる {{Glossary("falsy")}} です。</p> + +<p><code>false</code> と見ることができる式の例は、null、0、空文字列 ("")、あるいは、<code>undefined</code> と評価されるものです。</p> + +<p><code>&&</code> と <code>||</code> 演算子が真偽値ではない値である演算対象とともに用いることができても、それらは、真偽演算子と考えることができます。なぜなら、それらの戻り値は、常に、真偽値と見ることができるからです。</p> + +<h3 id=".E3.82.B7.E3.83.A7.E3.83.BC.E3.83.88.E3.82.B5.E3.83.BC.E3.82.AD.E3.83.83.E3.83.88.E8.A9.95.E4.BE.A1" name=".E3.82.B7.E3.83.A7.E3.83.BC.E3.83.88.E3.82.B5.E3.83.BC.E3.82.AD.E3.83.83.E3.83.88.E8.A9.95.E4.BE.A1">ショートサーキット評価</h3> + +<p>論理演算子は左から右へ評価されるため、論理演算子で左辺を評価した時点で論理式の結果が確定した場合には右辺の評価を行わないことを、ショートサーキット評価といいます。例えば、A && Bという論理式があった場合、Aがfalseなら、その時点で式全体の結果はfalseで確定するため、Bがどうであるかについてはチェックしません。:</p> + +<ul> + <li><code>false && (<em>anything</em>)</code> をショートサーキット評価すると、false になります。</li> + <li><code>true || (<em>anything</em>)</code> をショートサーキット評価すると、true になります。</li> +</ul> + +<p> 上記の式の anything の部分は評価されません。また、<strong>上記の式の anything の部分は (括弧で示しているとおり) ひとつの論理式ですので注意してください。</strong></p> + +<p>例えば、以下の 2 つの関数は等価です。</p> + +<pre class="brush: js">function shortCircuitEvaluation() { + doSomething() || doSomethingElse() +} + +function equivalentEvaluation() { + var flag = doSomething(); + if (!flag) { + doSomethingElse(); + } +} +</pre> + +<p>しかし、以下の式は等価ではありません。これは<a href="/ja/docs/Web/JavaScript/Reference/Operators/Operator_Precedence">演算子の優先順位</a>のためであり、右側の演算子をひとつの式にする (必要に応じて括弧でグループ化する) 必要性の重要度を高めています。</p> + +<pre class="brush: js">false && true || true // true を返す +false && (true || true) // false を返す</pre> + +<h3 id=".E8.AB.96.E7.90.86_AND_.28&&.29" name=".E8.AB.96.E7.90.86_AND_.28&&.29">論理 AND (<code>&&</code>)</h3> + +<p>以下のコードは、<code>&&</code> (論理 AND) 演算子の例を示しています。</p> + +<pre class="brush: js">a1 = true && true // t && t true を返します。 +a2 = true && false // t && f false を返します。 +a3 = false && true // f && t false を返します。 +a4 = false && (3 == 4) // f && f false を返します。 +a5 = "Cat" && "Dog" // t && t "Dog" を返します。 +a6 = false && "Cat" // f && t false を返します。 +a7 = "Cat" && false // t && f false を返します。 +</pre> + +<h3 id=".E8.AB.96.E7.90.86_OR_.28||.29" name=".E8.AB.96.E7.90.86_OR_.28||.29">論理 OR (<code>||</code>)</h3> + +<p>以下のコードは、<code>||</code> (論理 OR) 演算子の例を示しています。</p> + +<pre class="brush: js">o1 = true || true // t || t true を返します。 +o2 = false || true // f || t true を返します。 +o3 = true || false // t || f true を返します。 +o4 = false || (3 == 4) // f || f false を返します。 +o5 = "Cat" || "Dog" // t || t "Cat" を返します。 +o6 = false || "Cat" // f || t "Cat" を返します。 +o7 = "Cat" || false // t || f "Cat" を返します。 +</pre> + +<h3 id=".E8.AB.96.E7.90.86_NOT_.28.21.29" name=".E8.AB.96.E7.90.86_NOT_.28.21.29">論理 NOT (<code>!</code>)</h3> + +<p>以下のコードは、<code>!</code> (論理 NOT) 演算子の例を示しています。</p> + +<pre class="brush: js">n1 = !true // !t false を返します。 +n2 = !false // !f true を返します。 +n3 = !"Cat" // !t false を返します。 +</pre> + +<h3 id="Conversion_rules" name="Conversion_rules">変換規則</h3> + +<h4 id="Converting_AND_to_OR" name="Converting_AND_to_OR">AND から OR への変換</h4> + +<p>Boolean について以下の演算を行います:</p> + +<pre class="brush: js">bCondition1 && bCondition2</pre> + +<p>これは以下の演算と等価です:</p> + +<pre class="brush: js">!(!bCondition1 || !bCondition2)</pre> + +<h4 id="Converting_OR_to_AND" name="Converting_OR_to_AND">OR から AND への変換</h4> + +<p>Boolean について以下の演算を行います:</p> + +<pre class="brush: js">bCondition1 || bCondition2</pre> + +<p>これは以下の演算と等価です:</p> + +<pre class="brush: js">!(!bCondition1 && !bCondition2)</pre> + +<h4 id="Converting_between_NOTs" name="Converting_between_NOTs">NOT 間の変換</h4> + +<p>Boolean について以下の演算を行います:</p> + +<pre class="brush: js">!!bCondition</pre> + +<p>これは以下の演算と等価です:</p> + +<pre class="brush: js">bCondition</pre> + +<h3 id="Removing_nested_parentheses" name="Removing_nested_parentheses">入れ子の括弧を削除する</h3> + +<p>論理演算子は左から右へ評価されるため、複雑な式の中にある括弧をいくつかの規則に従って削除することができます。</p> + +<h4 id="Removing_nested_AND" name="Removing_nested_AND">入れ子の AND を削除する</h4> + +<p>Boolean について以下の複雑な演算を行います:</p> + +<pre class="brush: js">bCondition1 || (bCondition2 && bCondition3)</pre> + +<p>これは以下の演算と等価です:</p> + +<pre class="brush: js">bCondition1 || bCondition2 && bCondition3</pre> + +<h4 id="Removing_nested_OR" name="Removing_nested_OR">入れ子の OR を削除する</h4> + +<p>Boolean について以下の複雑な演算を行います:</p> + +<pre class="brush: js">bCondition1 && (bCondition2 || bCondition3)</pre> + +<p>これは以下の演算と等価です:</p> + +<pre class="brush: js">!(!bCondition1 || !bCondition2 && !bCondition3)</pre> + +<h2 id="Specifications" name="Specifications">仕様</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">仕様書</th> + <th scope="col">策定状況</th> + <th scope="col">コメント</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>最初期の定義</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-11.11')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>仕様書内のいくつかのセクションで定義: <a href="http://www.ecma-international.org/ecma-262/5.1/#sec-11.4.9">Logical NOT Operator</a>, <a href="http://www.ecma-international.org/ecma-262/5.1/#sec-11.11">Binary Logical Operators</a></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-binary-logical-operators')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>仕様書内のいくつかのセクションで定義: <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-logical-not-operator">Logical NOT Operator</a>, <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-binary-logical-operators">Binary Logical Operators</a></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-binary-logical-operators')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>仕様書内のいくつかのセクションで定義: <a href="http://tc39.github.io/ecma262/#sec-logical-not-operator">Logical NOT Operator</a>, <a href="http://tc39.github.io/ecma262/#sec-binary-logical-operators">Binary Logical Operators</a></td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">ブラウザ実装状況</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>機能</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>論理 AND (<code>&&</code>)</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>論理 OR (<code>||</code>)</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>論理 NOT (<code>!</code>)</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>機能</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>論理 AND (<code>&&</code>)</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>論理 OR (<code>||</code>)</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>論理 NOT (<code>!</code>)</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also" name="See_also">関連情報</h2> + +<ul> + <li><a href="/ja/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators">ビット演算子</a></li> + <li><a href="/ja/docs/Web/JavaScript/Reference/Global_Objects/Boolean">Boolean</a></li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/logical_or/index.html b/files/ja/web/javascript/reference/operators/logical_or/index.html new file mode 100644 index 0000000000..8fe1693e8a --- /dev/null +++ b/files/ja/web/javascript/reference/operators/logical_or/index.html @@ -0,0 +1,155 @@ +--- +title: 論理和 (||) +slug: Web/JavaScript/Reference/Operators/Logical_OR +tags: + - JavaScript + - Language feature + - Logical Operator + - Operator + - Reference + - 演算子 + - 言語機能 + - 論理演算子 +translation_of: Web/JavaScript/Reference/Operators/Logical_OR +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>論理和 (<code>||</code>) 演算子 (論理的分割) をオペランドの組み合わせに対して使用すると、オペランドのうち 1 つ以上が true である場合に true になります。一般的には {{jsxref("Boolean")}} (論理) 値で使用されます。その場合は論理値を返します。ただし <code>||</code> 演算子は実際には指定されたオペランドのうち一つの値を返すので、この演算子が論理値以外で使用された場合は、論理値以外の値を返すことになります。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-logical-or.html", "shorter")}}</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"><em>expr1</em> || <em>expr2</em> +</pre> + +<h2 id="Description" name="Description">解説</h2> + +<p><code>expr<strong>1</strong></code> が <code>true</code> に変換できる場合は <code>expr<strong>1</strong></code> を返し、それ以外の場合は <code>expr<strong>2</strong></code> を返します。</p> + +<p>ある値が <code>true</code> に変換できる場合、その値は真値 ({{Glossary("truthy")}}) と呼ばれます。ある値が <code>false</code> に変換できる場合、その値は偽値 ({{Glossary("falsy")}}) と呼ばれます。</p> + +<p>false に変換されうる式の例を示します。</p> + +<ul> + <li><code>null</code></li> + <li><code>NaN</code></li> + <li><code>0</code></li> + <li>空文字列 (<code>""</code> または <code>''</code> または <code>``</code>)</li> + <li><code>undefined</code></li> +</ul> + +<p><code>||</code> 演算子では論理値以外のオペランドを使用することができますが、返値が常に <a href="/ja/docs/Web/JavaScript/Data_structures#Boolean_type">boolean プリミティブ</a>に変換することが可能であるため、論理演算子と見なすことができます。返値 (または一般的な式) を対応する論理値に明示的に変換するには、二重の<a href="/ja/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Logical_NOT">否定演算子</a>または {{jsxref("Global_Objects/Boolean/Boolean", "Boolean")}} コンストラクターを使用してください。</p> + +<h3 id="Short-circuit_evaluation" name="Short-circuit_evaluation">短絡評価</h3> + +<p>論理和の式は左から右へと評価され、下記の規則を使用して「短絡」評価が可能なように評価されます。</p> + +<p><code>(真値の式) || <em>expr</em></code> は短絡評価で真値の式に評価されます。</p> + +<p>短絡とは、上記の <code><em>expr</em></code> の部分が<strong>評価されず</strong>、したがって、これを行うことの副作用が効果を及ぼさないことを意味します (例えば、 <code><em>expr</em></code> が関数呼び出しであった場合、この場所では呼び出されません)。これは、最初のオペランドが評価された時点で、すでに演算子の値が決定しているためです。例を示します。</p> + +<pre class="brush: js notranslate">function A(){ console.log('called A'); return false; } +function B(){ console.log('called B'); return true; } + +console.log( B() || A() ); +// 関数呼び出しによって "called B" がログ出力され、 +// それから true (演算子の結果の値) が出力されます。 +</pre> + +<h3 id="Operator_precedence" name="Operator_precedence">演算子の優先順位</h3> + +<p>以下の式は同じであるように見えるかもしれませんが、異なります。 <code>&&</code> 演算子は <code>||</code> 演算子よりも先に実行されるからです (<a href="/ja/docs/Web/JavaScript/Reference/Operators/Operator_Precedence">演算子の優先順位</a>参照)。</p> + +<pre class="brush: js notranslate">true || false && false // true を返す。 && が先に実行されるため +(true || false) && false // false を返す。演算子の優先順位が適用されないため</pre> + +<h2 id="Examples" name="Examples">例</h2> + +<h3 id="Using_OR" name="Using_OR">OR の使用</h3> + +<p>以下のコードは <code>||</code> (論理和) 演算子の例を示しています。</p> + +<pre class="brush: js notranslate">o1 = true || true // t || t returns true +o2 = false || true // f || t returns true +o3 = true || false // t || f returns true +o4 = false || (3 == 4) // f || f returns false +o5 = 'Cat' || 'Dog' // t || t returns "Cat" +o6 = false || 'Cat' // f || t returns "Cat" +o7 = 'Cat' || false // t || f returns "Cat" +o8 = '' || false // f || f returns false +o9 = false || '' // f || f returns "" +o10 = false || varObject // f || object returns varObject +</pre> + +<div class="blockIndicator note"> +<p><strong>注:</strong> この演算子を使用していくつかの変数に既定値を提供する場合、<em>偽値</em> が使用されないことに注意してください。{{jsxref("null")}} や {{jsxref("undefined")}} をフィルタリングする必要がある場合は、<a href="/ja/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator">Null 合体演算子</a>の使用を検討してください。</p> +</div> + +<h3 id="Conversion_rules_for_booleans" name="Conversion_rules_for_booleans">論理型の変換規則</h3> + +<h4 id="Converting_AND_to_OR" name="Converting_AND_to_OR">AND から OR への変換</h4> + +<p><strong>論理型</strong>に関する以下の操作は、</p> + +<pre class="brush: js notranslate">bCondition1 && bCondition2</pre> + +<p>常に以下のものと等しくなります。</p> + +<pre class="brush: js notranslate">!(!bCondition1 || !bCondition2)</pre> + +<h4 id="Converting_OR_to_AND" name="Converting_OR_to_AND">OR から AND への変換</h4> + +<p><strong>論理型</strong>に関する以下の操作は、</p> + +<pre class="brush: js notranslate">bCondition1 || bCondition2</pre> + +<p>常に以下のものと等しくなります。</p> + +<pre class="brush: js notranslate">!(!bCondition1 && !bCondition2)</pre> + +<h3 id="Removing_nested_parentheses" name="Removing_nested_parentheses">入れ子になった括弧の除去</h3> + +<p>論理式は左から右に評価されるので、いくつかのルールに従って複雑な式から括弧を削除することは常に可能です。</p> + +<p>以下の<strong>論理型</strong>に関する複合操作は、</p> + +<pre class="brush: js notranslate">bCondition1 && (bCondition2 || bCondition3)</pre> + +<p>常に以下のものと等しくなります。</p> + +<pre class="brush: js notranslate">!(!bCondition1 || !bCondition2 && !bCondition3)</pre> + +<h2 id="Specifications" name="Specifications">仕様書</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">仕様書</th> + </tr> + </thead> + <tbody> + <tr> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#prod-LogicalORExpression', 'Logical OR expression')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">ブラウザー実装状況</h2> + +<div class="hidden">このページの互換性一覧表は構造化データから生成されています。データに協力していただけるのであれば、 <a class="external" href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> をチェックアウトしてプルリクエストを送信してください。</div> + +<p>{{Compat("javascript.operators.logical_or")}}</p> + +<h2 id="See_also" name="See_also">関連情報</h2> + +<ul> + <li><a href="/ja/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator">Null 合体演算子 (<code>??</code>)</a></li> + <li>{{jsxref("Boolean")}}</li> + <li>{{Glossary("Truthy")}}</li> + <li>{{Glossary("Falsy")}}</li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/logical_or_assignment/index.html b/files/ja/web/javascript/reference/operators/logical_or_assignment/index.html new file mode 100644 index 0000000000..4f9a661684 --- /dev/null +++ b/files/ja/web/javascript/reference/operators/logical_or_assignment/index.html @@ -0,0 +1,93 @@ +--- +title: 論理和代入 (||=) +slug: Web/JavaScript/Reference/Operators/Logical_OR_assignment +tags: + - JavaScript + - Language feature + - Logical Operator + - Operator + - Reference +translation_of: Web/JavaScript/Reference/Operators/Logical_OR_assignment +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>論理和代入演算子 (<code>x ||= y</code>) は、<code>x</code> が {{Glossary("falsy")}} である場合にのみ代入します。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-logical-or-assignment.html")}}</div> + +<div class="hidden">The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> and send us a pull request.</div> + +<h2 id="構文">構文</h2> + +<pre class="syntaxbox notranslate"><em>expr1</em> ||= <em>expr2</em> +</pre> + +<h2 id="説明">説明</h2> + +<h3 id="短絡評価(ショートサーキット)">短絡評価(ショートサーキット)</h3> + +<p><a href="/docs/Web/JavaScript/Reference/Operators/Logical_OR">論理和</a>演算子は次のように動作します。</p> + +<pre class="brush: js notranslate">x || y; +// x が truthy の場合 x を返します +// x が truthy ではない場合 y を返します</pre> + +<p>論理和演算子は、1番目のオペランドが既に結果を決定していない場合にのみ、2番目のオペランドの評価を行う短絡評価をします。</p> + +<p>論理和代入も短絡評価されます。これは、<code>x ||= y</code> が以下と等価であることを意味します。</p> + +<pre class="brush: js notranslate">x || (x = y); +</pre> + +<p>そして、常に代入が行われる以下と等価ではありません。</p> + +<pre class="brush: js notranslate example-bad">x = x || y; +</pre> + +<p>注意: この動作は、数学的な代入演算子やビット代入演算子とは異なることに注意してください。</p> + +<h2 id="例">例</h2> + +<h3 id="デフォルトの内容を設定する">デフォルトの内容を設定する</h3> + +<p>"lyrics" 要素が空の場合は、<code><a href="/docs/Web/API/Element/innerHTML">innerHTML</a></code> をデフォルト値に設定します。</p> + +<pre class="brush: js notranslate">document.getElementById('lyrics').innerHTML ||= '<i>No lyrics.</i>'</pre> + +<p>ここでの短絡評価は、要素が不必要に更新されることがなく、追加のパースやレンダリング作業、フォーカスの損失などの望ましくない副作用を引き起こすことがないので、特に有益です。</p> + +<p>注意: チェック対象の API が返す値に注意してください。空の文字列({{Glossary("falsy")}} な値)が返される場合は、<code>||=</code> を使用する必要があります。それ以外の場合(戻り値が {{jsxref("null")}} または {{jsxref("undefined")}} の場合)は <code>??=</code> 演算子を使用します。</p> + +<h2 id="仕様">仕様</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">仕様書</th> + </tr> + </thead> + <tbody> + <tr> + </tr> + <tr> + <td>{{SpecName('Logical Assignment', '#sec-assignment-operators', 'Assignment operators')}}</td> + </tr> + </tbody> +</table> + +<h2 id="ブラウザの互換性">ブラウザの互換性</h2> + + + +<p>{{Compat("javascript.operators.logical_or_assignment")}}</p> + +<h2 id="関連情報">関連情報</h2> + +<ul> + <li><a href="/docs/Web/JavaScript/Reference/Operators/Logical_OR">論理和演算子 (||)</a></li> + <li><a href="/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator">Null合体演算子 (<code>??</code>)</a></li> + <li><a href="/docs/Web/JavaScript/Reference/Operators/Bitwise_OR_assignment">ビット論理和代入 (<code>|=</code>)</a></li> + <li>{{jsxref("Boolean")}}</li> + <li>{{Glossary("Truthy")}}</li> + <li>{{Glossary("Falsy")}}</li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/multiplication/index.html b/files/ja/web/javascript/reference/operators/multiplication/index.html new file mode 100644 index 0000000000..3921c0c56a --- /dev/null +++ b/files/ja/web/javascript/reference/operators/multiplication/index.html @@ -0,0 +1,74 @@ +--- +title: 乗算 (*) +slug: Web/JavaScript/Reference/Operators/Multiplication +tags: + - JavaScript + - Language feature + - Operator + - Reference +translation_of: Web/JavaScript/Reference/Operators/Multiplication +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>乗算演算子 (<code>*</code>) はオペランドの積を生成します。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-multiplication.html")}}</div> + +<div></div> + + + +<h2 id="構文">構文</h2> + +<pre class="syntaxbox notranslate"><strong>Operator:</strong> <var>x</var> * <var>y</var> +</pre> + +<h2 id="例">例</h2> + +<h3 id="数値を使用した乗算">数値を使用した乗算</h3> + +<pre class="brush: js notranslate"> 2 * 2 // 4 +-2 * 2 // -4 +</pre> + +<h3 id="無限大との乗算">無限大との乗算</h3> + +<pre class="brush: js notranslate">Infinity * 0 // NaN +Infinity * Infinity // Infinity</pre> + +<h3 id="非数との乗算">非数との乗算</h3> + +<pre class="brush: js notranslate">'foo' * 2 // NaN</pre> + +<h2 id="仕様">仕様</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">仕様</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-multiplicative-operators', 'Multiplication operator')}}</td> + </tr> + </tbody> +</table> + +<h2 id="ブラウザーの互換性">ブラウザーの互換性</h2> + + + +<p>{{Compat("javascript.operators.multiplication")}}</p> + +<h2 id="関連項目">関連項目</h2> + +<ul> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Addition">加算演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Subtraction">減算演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Division">除算演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Remainder">剰余演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Exponentiation">べき乗演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Increment">インクリメント演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Decrement">デクリメント演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Unary_negation">単項マイナス演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Unary_plus">単項プラス演算子</a></li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/multiplication_assignment/index.html b/files/ja/web/javascript/reference/operators/multiplication_assignment/index.html new file mode 100644 index 0000000000..86e53c206a --- /dev/null +++ b/files/ja/web/javascript/reference/operators/multiplication_assignment/index.html @@ -0,0 +1,61 @@ +--- +title: 乗算代入 (*=) +slug: Web/JavaScript/Reference/Operators/Multiplication_assignment +tags: + - Assignment operator + - JavaScript + - Language feature + - Operator + - Reference +translation_of: Web/JavaScript/Reference/Operators/Multiplication_assignment +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>乗算代入演算子 (<code>*=</code>) は、変数に右のオペランドの値を乗算し、結果を変数に代入します。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-multiplication-assignment.html")}}</div> + +<div></div> + + + +<h2 id="構文">構文</h2> + +<pre class="syntaxbox notranslate"><strong>Operator:</strong> x *= y +<strong>Meaning:</strong> x = x * y</pre> + +<h2 id="例">例</h2> + +<h3 id="乗算代入の使用">乗算代入の使用</h3> + +<pre class="brush: js notranslate">// 次の変数を想定 +// bar = 5 + +bar *= 2 // 10 +bar *= 'foo' // NaN</pre> + +<h2 id="仕様">仕様</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">仕様</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-assignment-operators', 'Assignment operators')}}</td> + </tr> + </tbody> +</table> + +<h2 id="ブラウザーの互換性">ブラウザーの互換性</h2> + + + +<p>{{Compat("javascript.operators.multiplication_assignment")}}</p> + +<h2 id="関連項目">関連項目</h2> + +<ul> + <li><a href="/docs/Web/JavaScript/Guide/Expressions_and_Operators#Assignment">代入演算子</a></li> + <li><a href="/docs/Web/JavaScript/Reference/Operators/Multiplication">乗算演算子</a></li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/new.target/index.html b/files/ja/web/javascript/reference/operators/new.target/index.html new file mode 100644 index 0000000000..b00f08cb4e --- /dev/null +++ b/files/ja/web/javascript/reference/operators/new.target/index.html @@ -0,0 +1,113 @@ +--- +title: new.target +slug: Web/JavaScript/Reference/Operators/new.target +tags: + - Classes + - ECMAScript 2015 + - JavaScript + - Language feature + - Reference +translation_of: Web/JavaScript/Reference/Operators/new.target +--- +<div>{{JSSidebar("Operators")}}</div> + +<p><strong><code>new.target</code></strong> プロパティを使用すると、関数やコンストラクタが <a href="/ja/docs/Web/JavaScript/Reference/Operators/new">new</a> 演算子を使用して呼び出されたかどうかを検出できます。コンストラクタや関数内で、<a href="/ja/docs/Web/JavaScript/Reference/Operators/new">new</a> 演算子でインスタンス生成すると、<code>new.target</code> はコンストラクタや関数への参照を返します。通常の関数呼び出しの場合、<code>new.target</code> は {{jsxref("undefined")}} です。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-newtarget.html")}}</div> + + + +<h2 id="Syntax" name="Syntax">構文</h2> + +<pre class="syntaxbox notranslate">new.target</pre> + +<h2 id="Description" name="Description">概要</h2> + +<p><code>new.target</code> の構文は、<code>new</code> キーワードとドット、プロパティ名 <code>target</code> で構成されています。通常、ドットの左側はプロパティアクセスが行われるオブジェクトですが、ここでの <code>new</code> はオブジェクトではありません。</p> + +<p><code>new.target</code> プロパティは、すべての関数で使用できる疑似的なプロパティです。</p> + +<p>クラスのコンストラクタでは、構築されたクラスを参照します。</p> + +<p>通常の関数では、<a href="/ja/docs/Web/JavaScript/Reference/Operators/new">new</a> 演算子を介して呼び出されたと仮定して、関数自体を参照します。それ以外の場合、<code>new.target</code> は {{jsxref("undefined")}} です。</p> + +<p><a href="/ja/docs/Web/JavaScript/Reference/Functions/Arrow_functions">アロー関数</a>では、<code>new.target</code> は周囲のスコープから継承されます。</p> + +<h2 id="Examples" name="Examples">例</h2> + +<h3 id="new.target_in_function_calls" name="new.target_in_function_calls">関数呼び出しにおいての <code>new.target</code> の使用</h3> + +<p>通常の関数呼び出しでは(コンストラクタ関数の呼び出しとは反対に)、<code>new.target</code> は {{jsxref("undefined")}} です。これにより、関数がコンストラクタとして <a href="/ja/docs/Web/JavaScript/Reference/Operators/new">new</a> で呼び出されたかを検出できます。</p> + +<pre class="brush: js notranslate">function Foo() { + if (!new.target) { throw 'Foo() must be called with new' } + console.log('Foo instantiated with new') +} + +new Foo() // logs "Foo instantiated with new" +Foo() // throws "Foo() must be called with new" +</pre> + +<h3 id="new.target_in_constructors" name="new.target_in_constructors">コンストラクタにおいての new.target</h3> + +<p>クラスコンストラクタで、<code>new.target</code> は <code>new</code> で直接実行されたコンストラクタを参照します。これは、コンストラクタは親クラスにあり、子コンストラクタからデリゲートされた場合も同様です。</p> + +<pre class="brush: js notranslate">class A { + constructor() { + console.log(new.target.name) + } +} + +class B extends A { constructor() { super() } } + +let a = new A() // logs "A" +let b = new B() // logs "B" + +class C { constructor() { console.log(new.target) } } +class D extends C { constructor() { super() } } + +let c = new C() // logs class C{constructor(){console.log(new.target);}} +let d = new D() // logs class D extends C{constructor(){super();}}</pre> + +<p class="summary">上記のクラス <code>C</code> と <code>D</code> の例から、<code>new.target</code> は初期化されたクラスのクラス定義を指しているように見えます。たとえば、<code>d</code> を <code>new D()</code> で初期化した場合は、<code>D</code> のクラス定義が出力され、同様に <code>c</code> の場合は <code>C</code> のクラスが出力されます。</p> + +<h2 id="Specifications" name="Specifications">仕様</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">仕様書</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-built-in-function-objects', 'Built-in Function Objects')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Specifications" name="Specifications">仕様</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">仕様書</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-built-in-function-objects', 'Built-in Function Objects')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">ブラウザー実装状況</h2> + + + +<p>{{Compat("javascript.operators.new_target")}}</p> + +<h2 id="See_also" name="See_also">関連情報</h2> + +<ul> + <li><a href="/ja/docs/Web/JavaScript/Reference/Functions">関数</a></li> + <li><a href="/ja/docs/Web/JavaScript/Reference/Classes">クラス</a></li> + <li><code><a href="/ja/docs/Web/JavaScript/Reference/Operators/new">new</a></code></li> + <li><code><a href="/ja/docs/Web/JavaScript/Reference/Operators/this">this</a></code></li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/new/index.html b/files/ja/web/javascript/reference/operators/new/index.html new file mode 100644 index 0000000000..3e9267d703 --- /dev/null +++ b/files/ja/web/javascript/reference/operators/new/index.html @@ -0,0 +1,181 @@ +--- +title: new 演算子 +slug: Web/JavaScript/Reference/Operators/new +tags: + - JavaScript + - Left-hand-side expressions + - Operator + - Reference + - 左辺値式 + - 演算子 +translation_of: Web/JavaScript/Reference/Operators/new +--- +<div>{{jsSidebar("Operators")}}</div> + +<p><span class="seoSummary"><strong><code>new</code> 演算子</strong>を使用すると、開発者はユーザー定義のオブジェクト型やコンストラクタ関数を持つ組み込みオブジェクト型のインスタンスを作成することができます。</span></p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-newoperator.html")}}</div> + +<h2 id="Syntax" name="Syntax">構文</h2> + +<pre class="syntaxbox notranslate">new <var>constructor</var>[([<var>arguments</var>])]</pre> + +<h3 id="Parameters" name="Parameters">引数</h3> + +<dl> + <dt><code><var>constructor</var></code></dt> + <dd>オブジェクトインスタンスの型を指定するクラスまたは関数です。</dd> +</dl> + +<dl> + <dt><code><var>arguments</var></code></dt> + <dd><code><var>constructor</var></code> が呼び出される際の引数のリストです。</dd> +</dl> + +<h2 id="Description" name="Description">解説</h2> + + +<p><strong><code>new</code></strong> 演算子は次のことを行います。</p> + +<ol> + <li>空白のプレーンな JavaScript オブジェクトを作成します。</li> + <li>他のオブジェクトを親プロトタイプとすることで、新しく作成されたオブジェクトと他のオブジェクトをリンク(コンストラクターを設定)します。 +</li> + <li>ステップ 1 で新しく作成されたオブジェクトを <code>this</code> コンテキストとして渡します。</li> + <li>関数がオブジェクトを返さない場合は <code>this</code> を返します。</li> +</ol> + +<p>ユーザー定義のオブジェクトを生成するには、2 つのステップが必要です。</p> + +<ol> + <li>関数を記述して、オブジェクトの型を定義します。</li> + <li><code>new</code> 演算子を使用して、オブジェクトのインスタンスを生成します。</li> +</ol> + +<p>オブジェクトの型を定義するために、オブジェクトの名称やプロパティを指定する、オブジェクトの型のための関数を作成します。オブジェクトは、別のオブジェクトそのものをプロパティとして持つことができます。後述の例をご覧ください。</p> + +<p>コード <code>new <em>Foo</em>(...)</code> を実行すると、以下の処理が行われます:</p> + +<ol> + <li><code><em>Foo</em>.prototype</code> を継承する、新しいオブジェクトを生成します。</li> + <li>指定した引数を伴ってコンストラクター関数 <code><em>Foo</em></code> が呼び出され、<code><a href="/ja/docs/Web/JavaScript/Reference/Operators/this">this</a></code> が新たに生成したオブジェクトに紐づけられます。<code>new <em>Foo</em></code> は <code>new <em>Foo</em>()</code> と等価です。すなわち、引数を指定しない場合は <code><em>Foo</em></code> が引数なしで呼び出されます。</li> + <li>コンストラクター関数が返すオブジェクト (null, false, 3.1415 などのプリミティブ型ではないもの) が、<code>new</code> 式の結果になります。コンストラクター関数が明示的にオブジェクトを返さない場合は、ステップ 1 で生成したオブジェクトを代わりに使用します。(通常、コンストラクターは値を返しませんが、通常のオブジェクト生成プロセスをオーバーライドしたい場合はそのようにすることができます。)</li> +</ol> + +<p>以前生成したオブジェクトに、いつでもプロパティを追加できます。例えば <code>car1.color = "black"</code> という構文は、<code>color</code> プロパティを <code>car1</code> に追加して、値として "<code>black</code>" を代入します。しかし、これは他のオブジェクトには影響を与えません。同じ型のすべてのオブジェクトに新たなプロパティを追加するには、<code>Car</code> オブジェクト型の定義に対してプロパティを追加しなければなりません。</p> + +<p><code><a href="/ja/docs/Web/JavaScript/Reference/Global_Objects/Function/prototype">Function.prototype</a></code> プロパティを使用して、以前定義したオブジェクトに対して共有のプロパティを追加できます。これはオブジェクト型のあるインスタンスのプロパティではなく、関数を使用して生成したすべてのオブジェクトで共有するプロパティを定義します。以下のコードでは <code>Car</code> 型のオブジェクトすべてに対して color プロパティを値 <code>"original color"</code> で定義しています。また、インスタンスオブジェクト <code>car1</code> の color プロパティに文字列の値 "<code>black</code>" を上書きしています。詳しくは <a href="/ja/docs/Web/JavaScript/Reference/Global_Objects/Function/prototype">prototype</a> をご覧ください。</p> + +<pre class="brush: js notranslate">function Car() {} +car1 = new Car(); +car2 = new Car(); + +console.log(car1.color); // undefined + +Car.prototype.color = "original color"; +console.log(car1.color); // original color + +car1.color = 'black'; +console.log(car1.color); // black + +console.log(car1.__proto__.color) //original color +console.log(car2.__proto__.color) //original color +console.log(car1.color) // black +console.log(car2.color) // original color +</pre> + +<div class="note"> +<p><code>new</code> 演算子を記述しなかった場合、<strong>コンストラクターは通常の関数として扱われ</strong>、<em>オブジェクトを作成しません</em>。その際、<code>this</code> の値も異なるものになります。</p> +</div> + +<h2 id="Examples" name="Examples">例</h2> + +<h3 id="Object_type_and_object_instance" name="Object_type_and_object_instance">オブジェクトの型とオブジェクトのインスタンス</h3> + +<p>自動車用のオブジェクト型を作成したいとします。このオブジェクト型は <code>Car</code> という名前で、make、model、year というプロパティを持たせます。そのために、以下の関数を記述します。</p> + +<pre class="brush: js notranslate">function Car(make, model, year) { + this.make = make; + this.model = model; + this.year = year; +} +</pre> + +<p>これで、以下のように <code>mycar</code> という名前のオブジェクトを生成できます。</p> + +<pre class="brush: js notranslate">var mycar = new Car('Eagle', 'Talon TSi', 1993); +</pre> + +<p>この構文は <code>mycar</code> を生成して、プロパティに特定の値を代入しています。<code>mycar.make</code> の値は文字列 "Eagle"、<code>mycar.year</code> の値は整数 1993 などとなります。</p> + +<p><code>new</code> を呼び出して、<code>car</code> オブジェクトをいくつも生成できます。例えば、</p> + +<pre class="brush: js notranslate">var kenscar = new Car('Nissan', '300ZX', 1992); +</pre> + +<h3 id="Object_property_that_is_itself_another_object" name="Object_property_that_is_itself_another_object">それ自身が別のオブジェクトであるプロパティ</h3> + +<p>以下のように、<code>Person</code> という名前のオブジェクトを定義します:</p> + +<pre class="brush: js notranslate">function Person(name, age, sex) { + this.name = name; + this.age = age; + this.sex = sex; +} +</pre> + +<p>そして、以下のように <code>Person</code> オブジェクトのインスタンスを新たに 2 つ生成します。</p> + +<pre class="brush: js notranslate">var rand = new Person('Rand McNally', 33, 'M'); +var ken = new Person('Ken Jones', 39, 'M'); +</pre> + +<p>さらに <code>Car</code> の定義を、以下のように <code>Person</code> オブジェクトを値としてとる <code>owner</code> プロパティを持つように書き換えます:</p> + +<pre class="brush: js notranslate">function Car(make, model, year, owner) { + this.make = make; + this.model = model; + this.year = year; + this.owner = owner; +} +</pre> + +<p>新しいオブジェクトを生成するため、以下のように使用します。</p> + +<pre class="brush: js notranslate">var car1 = new Car('Eagle', 'Talon TSi', 1993, rand); +var car2 = new Car('Nissan', '300ZX', 1992, ken); +</pre> + +<p>この構文では新しいオブジェクトを生成するときに文字列や整数のリテラル値を渡す代わりに、owner のパラメータとしてオブジェクト <code>rand</code> や <code>ken</code> を渡しています。<code>car2</code> の所有者名を調べるには、以下のようにしてプロパティにアクセスできます。</p> + +<pre class="brush: js notranslate">car2.owner.name +</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-new-operator', 'The new Operator')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">ブラウザー実装状況</h2> + + + +<p>{{Compat("javascript.operators.new")}}</p> + +<h2 id="See_also" name="See_also">関連情報</h2> + +<ul> + <li>{{jsxref("Function")}}</li> + <li>{{jsxref("Reflect.construct()")}}</li> + <li>{{jsxref("Object.prototype")}}</li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/nullish_coalescing_operator/index.html b/files/ja/web/javascript/reference/operators/nullish_coalescing_operator/index.html new file mode 100644 index 0000000000..3302e2e02b --- /dev/null +++ b/files/ja/web/javascript/reference/operators/nullish_coalescing_operator/index.html @@ -0,0 +1,155 @@ +--- +title: Null 合体 (??) +slug: Web/JavaScript/Reference/Operators/Nullish_coalescing_operator +tags: + - JavaScript + - Language feature + - Operator + - Reference + - nullish coalescing +translation_of: Web/JavaScript/Reference/Operators/Nullish_coalescing_operator +--- +<p>{{JSSidebar("Operators")}}</p> + +<p><strong>Null 合体演算子 (<code>??</code>)</strong> は論理演算子の一種です。この演算子は左辺が {{jsxref("null")}} または {{jsxref("undefined")}} の場合に右の値を返し、それ以外の場合に左の値を返します。</p> + +<p><a href="/ja/docs/Web/JavaScript/Reference/Operators/Logical_Operators">OR 演算子 (<code>||</code>)</a> と違い、<code>null</code> と <code>undefined</code> 以外の <em><a href="/ja/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Description">falsy</a></em> な値のときには左の値を返します。つまり、左辺が <code>''</code> や <code>0</code> の場合は左の値を評価して返します。その他の例については以下を参照してください。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-nullishcoalescingoperator.html")}}</div> + +<p class="hidden">The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> and send us a pull request.<br> + See <a href="https://github.com/mdn/interactive-examples/pull/1482#issuecomment-553841750">PR #1482</a> regarding the addition of this example.</p> + +<h2 id="Syntax" name="Syntax">構文</h2> + +<pre class="syntaxbox notranslate"><var>leftExpr</var> ?? <var>rightExpr</var> +</pre> + +<h2 id="Description" name="Description">説明</h2> + +<p>Null 合体演算子は左辺が {{jsxref("null")}} または {{jsxref("undefined")}} の場合に右辺の値を返します。</p> + +<h3 id="Assigning_a_default_value_to_a_variable" name="Assigning_a_default_value_to_a_variable">変数にデフォルト値を代入する</h3> + +<p>以前は、変数にデフォルト値を代入したい場合、一般的なパターンは OR 演算子 (<code><a href="/ja/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Logical_OR_2">||</a></code>) を使用することでした:</p> + +<pre class="brush: js notranslate">let foo; + +// foo is never assigned any value so it is still undefined +let someDummyText = foo || 'Hello!';</pre> + +<p>しかし、<code>||</code> が論理演算子であるため、左辺の値は評価によって強制的にブール値になり、falsy な値 (<code>0</code>, <code>''</code>, <code>NaN</code>, <code>null</code>, <code>undefined</code>) が返されることはありません。この動作は、<code>0</code> や <code>''</code>, <code>NaN</code> を有効な値と考えている場合、予期せぬ結果を引き起こす可能性があります。</p> + +<pre class="brush: js notranslate">let count = 0; +let text = ""; + +let qty = count || 42; +let message = text || "hi!"; +console.log(qty); // 42 and not 0 +console.log(message); // "hi!" and not "" +</pre> + +<p>Null 合体演算子は、左辺の値が <code>null</code> もしくは <code>undefined</code> のどちらか (その他の falsy な値は含みません) に評価された場合にのみ右辺の値を返すことで、この潜在的な危険を回避します:</p> + +<pre class="brush: js notranslate">let myText = ''; // An empty string (which is also a falsy value) + +let notFalsyText = myText || 'Hello world'; +console.log(notFalsyText); // Hello world + +let preservingFalsy = myText ?? 'Hi neighborhood'; +console.log(preservingFalsy); // '' (as myText is neither undefined nor null) +</pre> + +<h3 id="Short-circuiting" name="Short-circuiting">短絡評価</h3> + +<p>OR 演算子や AND 演算子と同様に、左辺が <code>null</code> でも <code>undefined</code> でもないことが証明された場合、右辺の式は評価されません。</p> + +<pre class="brush: js notranslate">function A() { console.log('A was called'); return undefined;} +function B() { console.log('B was called'); return false;} +function C() { console.log('C was called'); return "foo";} + +console.log( A() ?? C() ); +// logs "A was called" then "C was called" and then "foo" +// as A() returned undefined so both expressions are evaluated + +console.log( B() ?? C() ); +// logs "B was called" then "false" +// as B() returned false (and not null or undefined), the right +// hand side expression was not evaluated +</pre> + +<h3 id="No_chaining_with_AND_or_OR_operators" name="No_chaining_with_AND_or_OR_operators">AND 演算子、OR 演算子とつなげて使わない</h3> + +<p>AND 演算子 (<code>&&</code>) と OR 演算子 (<code>||</code>) を直接 <code>??</code> とつなげて使うことはできません。このような場合 <code><a href="/ja/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError">SyntaxError</a></code> が発生します。</p> + +<pre class="brush: js example-bad notranslate">null || undefined ?? "foo"; // raises a SyntaxError +true || undefined ?? "foo"; // raises a SyntaxError</pre> + +<p>ただし、カッコを付けて明示的に優先順位を示すのは正しいやり方です。</p> + +<pre class="brush: js example-good notranslate">(null || undefined) ?? "foo"; // returns "foo" +</pre> + +<h3 id="Relationship_with_the_optional_chaining_operator_." name="Relationship_with_the_optional_chaining_operator_.">オプショナルチェイニング演算子 (<code>?.</code>) との関係</h3> + +<p>Null 合体演算子は、<code>null</code> と <code>undefined</code> を特定の値として扱いますが、<a href="/ja/docs/Web/JavaScript/Reference/Operators/Optional_chaining">オプショナルチェイニング演算子 (<code>?.</code>)</a> も同様の扱いをします。この演算子は、<code>null</code> または <code>undefined</code> である可能性のあるオブジェクトのプロパティにアクセスするのに便利です。</p> + +<pre class="brush: js notranslate">let foo = { someFooProp: "hi" }; + +console.log(foo.someFooProp?.toUpperCase()); // "HI" +console.log(foo.someBarProp?.toUpperCase()); // undefined +</pre> + +<h2 id="Examples" name="Examples">例</h2> + +<p>次の例では、デフォルト値を設定していますが、<code>null</code> や <code>undefined</code> 以外の値は保持されます。</p> + +<pre class="brush: js notranslate">const nullValue = null; +const emptyText = ""; // falsy +const someNumber = 42; + +const valA = nullValue ?? "default for A"; +const valB = emptyText ?? "default for B"; +const valC = someNumber ?? 0; + +console.log(valA); // "default for A" +console.log(valB); // "" (as the empty string is not null or undefined) +console.log(valC); // 42 +</pre> + +<h2 id="Specifications" name="Specifications">仕様</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">仕様書</th> + </tr> + </thead> + <tbody> + <tr> + <td> + <p>{{SpecName('ESDraft', '#prod-Nulli', 'nullish coalescing expression')}}</p> + </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">ブラウザー実装状況</h2> + + + +<p>{{Compat("javascript.operators.nullish_coalescing")}}</p> + +<h3 id="Implementation_Progress" name="Implementation_Progress">実装の進捗</h3> + +<p>この機能はまだブラウザー間相互運用の安定性に達していないため、以下の表はこの機能の日々の実装状況を示しています。このデータは、 JavaScript の標準テストスイートである <a href="https://github.com/tc39/test262">Test262</a> で、該当する機能テストを Nightly ビルド、または各ブラウザーの JavaScript エンジンの最新リリースで実行することで生成されます。</p> + +<div>{{EmbedTest262ReportResultsTable("coalesce-expression")}}</div> + +<h2 id="See_also" name="See_also">関連情報</h2> + +<ul> + <li><a href="/ja/docs/Web/JavaScript/Reference/Operators/Optional_chaining">オプショナルチェイニング演算子</a></li> + <li><a href="/ja/docs/Web/JavaScript/Reference/Operators/Logical_Operators">論理 OR (<code>||</code>) 演算子</a></li> + <li><a href="/ja/docs/Web/JavaScript/Reference/Functions/Default_parameters">デフォルト引数</a></li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/object_initializer/index.html b/files/ja/web/javascript/reference/operators/object_initializer/index.html new file mode 100644 index 0000000000..305f7259ed --- /dev/null +++ b/files/ja/web/javascript/reference/operators/object_initializer/index.html @@ -0,0 +1,311 @@ +--- +title: オブジェクト初期化子 +slug: Web/JavaScript/Reference/Operators/Object_initializer +tags: + - ECMAScript 2015 + - JSON + - JavaScript + - Literal + - Methods + - Object + - Primary Expression + - computed + - mutation + - properties +translation_of: Web/JavaScript/Reference/Operators/Object_initializer +--- +<div>{{JsSidebar("Operators")}}</div> + +<p>オブジェクトは <a href="/ja/docs/Web/JavaScript/Reference/Global_Objects/Object"><code>new Object()</code></a>、<code><a href="/ja/docs/Web/JavaScript/Reference/Global_Objects/Object/create">Object.create()</a></code>、<em>リテラル</em>表記法 (<em>initializer</em> 表記法) を使用して初期化されます。オブジェクト初期化子はオブジェクトのプロパティ名と関連した値のゼロ以上のペアのリストです。中括弧 (<code>{}</code>) で囲まれます。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-objectinitializer.html")}}</div> + + + +<h2 id="Syntax" name="Syntax">構文</h2> + +<pre class="brush: js">var o = {}; +var o = { a: 'foo', b: 42, c: {} }; + +var a = 'foo', b = 42, c = {}; +var o = {a: a, b: b, c: c}; + +var o = { + <var>property: function </var>(<var>parameters</var>) {}, + get <var>property</var>() {}, + set <var>property</var>(<var>value</var>) {}, +}; +</pre> + +<h3 id="New_notations_in_ECMAScript_2015" name="New_notations_in_ECMAScript_2015">ECMAScript 2015 での新しい表記法</h3> + +<p>これらの表記をサポートするための互換性の表を参照してください。非サポート環境では、これらの表記は、構文エラーにつながります。</p> + +<pre class="brush: js">// Shorthand property names (ES2015) +var a = 'foo', b = 42, c = {}; +var o = {a, b, c}; + +// Shorthand method names (ES2015) +var o = { + <var>property</var>(<var>parameters</var>) {} +}; + +// Computed property names (ES2015) +var prop = 'foo'; +var o = { + [prop]: 'hey', + ['b' + 'ar']: 'there' +};</pre> + +<h2 id="Description" name="Description">説明</h2> + +<p>オブジェクト初期化子は、{{jsxref("Object")}} の初期化を表す式です。オブジェクトはオブジェクトを表す<em>プロパティ</em>で構成されます。オブジェクトプロパティの値は特定の {{Glossary("primitive")}} データ型か他のオブジェクトのどちらかを含みます。</p> + +<h3 id="Creating_objects" name="Creating_objects">オブジェクトの生成</h3> + +<p>プロパティを持たない空のオブジェクトは下記のように中括弧を記述することで生成されます。</p> + +<pre class="brush: js">var object = {};</pre> + +<p><em>リテラル</em>表記法、<em>initializer</em> 表記法の利点は中括弧内にプロパティをもつオブジェクトをすばやく生成できる点です。また、カンマで区切られた <code>key: value</code> のペアを記述することでプロパティ値の生成も可能です。以下に、三つのプロパティをもつオブジェクトを生成する方法を記します。キーは <code>"foo"</code>、<code>"age"</code>、<code>"baz"</code> であり、各々のキーの値は、文字列の <code>"bar"</code>、数値の <code>42</code> 、そして <code>baz</code> はオブジェクトがプロパティ値となります。</p> + +<pre class="brush: js">var object = { + foo: 'bar', + age: 42, + baz: {myProp: 12}, +}</pre> + +<h3 id="Accessing_properties" name="Accessing_properties">プロパティへのアクセス</h3> + +<p>一度オブジェクトを生成した後も、プロパティにアクセスすることができます。その方法は「ドット表記法」か「ブラケット表記法」と言われます。詳細については、<a href="/ja/docs/Web/JavaScript/Reference/Operators/Property_Accessors">プロパティへのアクセス</a>をご覧ください。</p> + +<pre class="brush: js">object.foo; // "bar" +object['age']; // 42 + +object.foo = 'baz'; +</pre> + +<h3 id="Property_definitions" name="Property_definitions">プロパティの定義</h3> + +<p>初期化構文を使用してプロパティを記譜する方法について既に学びました。多くの場合、コード内には、オブジェクトに設定したい変数があります。下記のコードをご覧ください。:</p> + +<pre class="brush: js">var a = 'foo', + b = 42, + c = {}; + +var o = { + a: a, + b: b, + c: c +};</pre> + +<p>ECMAScript 2015 では、同じことを達成するために利用可能な短い表記があります。:</p> + +<pre class="brush: js">var a = 'foo', + b = 42, + c = {}; + +// Shorthand property names (ES2015) +var o = {a, b, c}; + +// In other words, +console.log((o.a === {a}.a)); // true +</pre> + +<h4 id="Duplicate_property_names" name="Duplicate_property_names">重複したプロパティ名</h4> + +<p>プロパティに対して同じ名前を使用するとき、二番目のプロパティは最初のプロパティを上書きします。</p> + +<pre class="brush: js">var a = {x: 1, x: 2}; +console.log(a); // {x: 2} +</pre> + +<p>ECMAScript 5 の strict モードのコードでは、重複したプロパティの名前は {{jsxref("SyntaxError")}} とみなされます。実行時に重複を可能にする計算されたプロパティ名の導入により、ECMAScript 2015 ではこの制限は取り除かれました。</p> + +<pre class="brush: js">function haveES2015DuplicatePropertySemantics() { + 'use strict'; + try { + ({prop: 1, prop: 2}); + + // No error thrown, duplicate property names allowed in strict mode + return true; + } catch (e) { + // Error thrown, duplicates prohibited in strict mode + return false; + } +}</pre> + +<h3 id="Method_definitions" name="Method_definitions">メソッドの定義</h3> + +<p>オブジェクトのプロパティは <a href="/ja/docs/Web/JavaScript/Reference/Functions">function</a>、<a href="/ja/docs/Web/JavaScript/Reference/Functions/get">getter</a> メソッド、<a href="/ja/docs/Web/JavaScript/Reference/Functions/set">setter </a>メソッドも参照することができます</p> + +<pre class="brush: js">var o = { + <var>property: function </var>(<var>parameters</var>) {}, + get <var>property</var>() {}, + set <var>property</var>(<var>value</var>) {}, +};</pre> + +<p>ECMAScript 2015 では、省略表記が利用可能です。そのため、キーワード "function" はもはや必要ではありません。</p> + +<pre class="brush: js">// Shorthand method names (ES2015) +var o = { + <var>property</var>(<var>parameters</var>) {}, + *<var>generator</var>() {} +};</pre> + +<p>ECMAScript 2015 では、その値がジェネレーター関数であるプロパティを簡潔に定義する方法があります。:</p> + +<pre class="brush: js">var o = { + *<var>generator</var>() { + ........... + } +};</pre> + +<p>ECMAScript 5 では、下記のように記述します (しかし、ES5 はジェネレーターを持たないことに注意してください):</p> + +<pre class="brush: js">var o = { + generator:<var> function* </var>() { + ........... + } +};</pre> + +<p>メソッドの詳細や例については、<a href="/ja/docs/Web/JavaScript/Reference/Functions/Method_definitions">メソッド定義</a>をご覧ください。</p> + +<h3 id="Computed_property_names" name="Computed_property_names">計算されたプロパティ名</h3> + +<p>ECMAScript 2015 から、オブジェクト初期化子構文も計算されたプロパティ名をサポートします。括弧 <code>[]</code> の中に式を記述でき、それが計算されてプロパティ名として使用されます。これは、あなたが既にプロパティを読み込んだり設定したりするために使用したことがあるかもしれない、<a href="/ja/docs/Web/JavaScript/Reference/Operators/Property_Accessors">メンバー演算子</a>構文のブラケット表記を思い起こさせます。今では、オブジェクトリテラルでも同様な構文を使うことができます:</p> + +<pre class="brush: js">// Computed property names (ES2015) +var i = 0; +var a = { + ['foo' + ++i]: i, + ['foo' + ++i]: i, + ['foo' + ++i]: i +}; + +console.log(a.foo1); // 1 +console.log(a.foo2); // 2 +console.log(a.foo3); // 3 + +var param = 'size'; +var config = { + [param]: 12, + ['mobile' + param.charAt(0).toUpperCase() + param.slice(1)]: 4 +}; + +console.log(config); // {size: 12, mobileSize: 4}</pre> + +<h3 id="Spread_properties" name="Spread_properties">スプレッドプロパティ</h3> + +<p><a href="https://github.com/tc39/proposal-object-rest-spread">ECMAScript proposal の Rest/Spread プロパティ</a> (ステージ 4) オブジェクトリテラルに<a href="/ja/docs/Web/JavaScript/Reference/Operators/Spread_operator">スプレッド</a>プロパティを追加します。 渡されたオブジェクトから新しいオブジェクトに独自の列挙可能なプロパティをコピーします。</p> + +<p>{{jsxref("Object.assign()")}} を使うよりも短いコードで prototype を除いた浅いコピーの作成や、マージしたオブジェクトの作成を書けます。</p> + +<pre class="brush: js">var obj1 = { foo: 'bar', x: 42 }; +var obj2 = { foo: 'baz', y: 13 }; + +var clonedObj = { ...obj1 }; +// Object { foo: "bar", x: 42 } + +var mergedObj = { ...obj1, ...obj2 }; +// Object { foo: "baz", x: 42, y: 13 }</pre> + +<p>{{jsxref("Object.assign()")}} は <a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Functions/set">setters</a> をトリガーしますが、スプレッド構文はトリガーできません。</p> + +<h3 id="Prototype_mutation" name="Prototype_mutation">プロトタイプ変異</h3> + +<p><code>__proto__: value</code> 形式、または <code>"__proto__": value</code> 形式のプロパティ定義は、<code>__proto__</code> 名をもつプロパティを生成しません。かわりに、与えられた値がオブジェクトか <a href="/ja/docs/Web/JavaScript/Reference/Global_Objects/null"><code>null</code></a> の場合、その値に生成されたオブジェクトの <code>[[Prototype]]</code> を変更します (その値がオブジェクト、または null ではない場合、オブジェクトは変更されません)。</p> + +<pre class="brush: js">var obj1 = {}; +assert(Object.getPrototypeOf(obj1) === Object.prototype); + +var obj2 = {__proto__: null}; +assert(Object.getPrototypeOf(obj2) === null); + +var protoObj = {}; +var obj3 = {'__proto__': protoObj}; +assert(Object.getPrototypeOf(obj3) === protoObj); + +var obj4 = {__proto__: 'not an object or null'}; +assert(Object.getPrototypeOf(obj4) === Object.prototype); +assert(!obj4.hasOwnProperty('__proto__')); +</pre> + +<p>単一のプロトタイプの変異のみ、オブジェクトリテラルに許可されています: すなわち、複数のプロトタイプの変異は構文エラーです。</p> + +<p>"colon" 表記法を使用しないプロパティ定義はプロトタイプ変異ではありません。: 任意の他の名称を使用する同様の定義と同じように動作するプロパティ定義です。</p> + +<pre class="brush: js">var __proto__ = 'variable'; + +var obj1 = {__proto__}; +assert(Object.getPrototypeOf(obj1) === Object.prototype); +assert(obj1.hasOwnProperty('__proto__')); +assert(obj1.__proto__ === 'variable'); + +var obj2 = {__proto__() { return 'hello'; }}; +assert(obj2.__proto__() === 'hello'); + +var obj3 = { ['__prot' + 'o__']: 17 }; +assert(obj3.__proto__ === 17); +</pre> + +<h2 id="Object_literal_notation_vs_JSON" name="Object_literal_notation_vs_JSON">オブジェクトリテラル表記法 vs JSON</h2> + +<p>オブジェクトリテラル表記法は <strong>J</strong>ava<strong>S</strong>cript <strong>O</strong>bject <strong>N</strong>otation (<a href="/ja/docs/Glossary/JSON">JSON</a>) とは異なります。それらは似ていますが、それらの間には違いがあります。:</p> + +<ul> + <li>JSON は、<code>"property": value</code> 構文を使用するプロパティ定義<em>のみ</em>許可します。プロパティ名称は二重引用符で囲まなければなりません。そして、その定義は簡略にすることはできません。</li> + <li>JSON ではその値は strings、numbers、arrays、<code>true</code>、<code>false</code>、<code>null</code>、別の (JSON) オブジェクトのみです。</li> + <li>関数の値 (上記"{{anch("Method definitions", "メソッド")}}"を参照) は JSON では値を割り当てることができません。</li> + <li>{{jsxref("Date")}} のようなオブジェクトは {{jsxref("JSON.parse()")}} の後で string になります。</li> + <li>{{jsxref("JSON.parse()")}} は計算されたプロパティ名を拒否し、エラーがスローされます。</li> +</ul> + +<h2 id="Specifications" name="Specifications">仕様</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">仕様</th> + <th scope="col">ステータス</th> + <th scope="col">コメント</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>初期定義。</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-11.1.5', 'Object Initializer')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td><a href="/ja/docs/Web/JavaScript/Reference/Functions/get">getter</a> と <a href="/ja/docs/Web/JavaScript/Reference/Functions/set">setter</a> が追加されました。</td> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-object-initializer', 'Object Initializer')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>簡略表現メソッド/プロパティの名称と計算されたプロパティ名が追加されました。</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-object-initializer', 'Object Initializer')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">ブラウザー実装状況</h2> + +<div> + + +<p>{{Compat("javascript.operators.object_initializer")}}</p> +</div> + +<h2 id="See_also" name="See_also">関連情報</h2> + +<ul> + <li><a href="/ja/docs/Web/JavaScript/Reference/Operators/Property_Accessors">メンバー演算子</a></li> + <li><code><a href="/ja/docs/Web/JavaScript/Reference/Functions/get">get</a></code> / <code><a href="/ja/docs/Web/JavaScript/Reference/Functions/set">set</a></code></li> + <li><a href="/ja/docs/Web/JavaScript/Reference/Functions/Method_definitions">メソッド定義</a></li> + <li><a href="/ja/docs/Web/JavaScript/Reference/Lexical_grammar">字句文法</a></li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/operator_precedence/index.html b/files/ja/web/javascript/reference/operators/operator_precedence/index.html new file mode 100644 index 0000000000..69b9c5c76b --- /dev/null +++ b/files/ja/web/javascript/reference/operators/operator_precedence/index.html @@ -0,0 +1,483 @@ +--- +title: 演算子の優先順位 +slug: Web/JavaScript/Reference/Operators/Operator_Precedence +tags: + - Guide + - JavaScript + - precedence + - ガイド + - 優先順位 +translation_of: Web/JavaScript/Reference/Operators/Operator_Precedence +--- +<div>{{jsSidebar("Operators")}}</div> + +<p><strong>演算子の優先順位</strong>は、演算子が互いにどのように解析されるかを決定します。優先度の高い演算子は、優先度の低い演算子のオペランドになります。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-operatorprecedence.html")}}</div> + +<div class="hidden">このデモのソースファイルは GitHub リポジトリに格納されています。デモプロジェクトに協力したい場合は、<a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> をクローンしてプルリクエストを送信してください。</div> + +<h2 id="Precedence_And_Associativity" name="Precedence_And_Associativity">優先度と結合性</h2> + +<p>以下の表現で記述できる式を考えてみましょう。なお、OP<sub>1</sub> と OP<sub>2</sub> は演算子に置き換わります。</p> + +<pre class="syntaxbox notranslate">a OP<sub>1</sub> b OP<sub>2</sub> c</pre> + +<p><code>OP<sub>1</sub></code> と <code>OP<sub>2</sub></code> の優先順位 (下記の一覧表を参照) が異なる場合は、優先順位の高い演算子が先に実行され、結合性は関係ありません。コードの中で加算が先に書かれているにもかかわらず、乗算の方が加算よりも優先順位が高く、先に実行されていることを確認してください。</p> + +<pre class="brush: js notranslate">console.log(3 + 10 * 2); // 23 を出力 +console.log(3 + (10 * 2)); // 括弧の優先順位が高いので、23 を出力 +console.log((3 + 10) * 2); // 括弧が順位を変更するので 26 を出力 +</pre> + +<p>左結合 (左から右) は <code>(a OP<sub>1</sub> b) OP<sub>2</sub> c</code> のように処理されることであり、右結合 (右から左) は <code>a OP<sub>1</sub> (b OP<sub>2</sub> c)</code> のように解釈されることです。代入演算子は右結合なので、このように書くことができます。</p> + +<pre class="brush: js notranslate">a = b = 5; // a = (b = 5); と書いたのと同じ +</pre> + +<p>これで、<code>a</code> と <code>b</code> が 5 の値を得るという期待通りの結果を得ることができます。これは代入演算子が代入した値を返すためです。まず <code>b</code> に 5 が設定されます。そして <code>a</code> にも、代入演算子の右オペランドである <code>b = 5</code> が返す 5 が設定されるのです。</p> + +<p>他の例として、べき乗演算子だけが右結合性を持ちますが、他の算術演算子は左結合性を持ちます。興味深いのは、結合性や優先順位に関係なく、評価の順序は常に左から右になることです。</p> + +<table class="standard-table"> + <tbody> + <tr> + <td>コード</td> + <td>出力結果</td> + </tr> + <tr> + <td> + <pre class="brush: js notranslate"> +function echo(name, num) { + console.log("Evaluating the " + name + " side"); + return num; +} +// 除算演算子 (/) の場合 +console.log(echo("left", 6) / echo("right", 2)); +</pre> + </td> + <td> + <pre class="notranslate"> +Evaluating the left side +Evaluating the right side +3 +</pre> + </td> + </tr> + <tr> + <td> + <pre class="brush: js notranslate"> +function echo(name, num) { + console.log("Evaluating the " + name + " side"); + return num; +} +// べき乗演算子 (**) の場合 +console.log(echo("left", 2) ** echo("right", 3));</pre> + </td> + <td> + <pre class="notranslate"> +Evaluating the left side +Evaluating the right side +8</pre> + </td> + </tr> + </tbody> +</table> + +<p>結合性の違いは、同じ優先順位の演算子が複数存在する場合に現れます。上の例のように演算子が一つだけの場合や、演算子の優先順位が異なる場合は、結合性は出力に影響を与えません。下の例では、同じ演算子が複数使われている場合に、結合性が出力結果にどのような影響を与えるかを見てみましょう。</p> + +<table class="standard-table"> + <tbody> + <tr> + <td>コード</td> + <td>出力結果</td> + </tr> + <tr> + <td> + <pre class="brush: js notranslate"> +function echo(name, num) { + console.log("Evaluating the " + name + " side"); + return num; +} +// 除算演算子 (/) の場合 +console.log(echo("left", 6) / echo("middle", 2) / echo("right", 3)); +</pre> + </td> + <td> + <pre class="notranslate"> +Evaluating the left side +Evaluating the middle side +Evaluating the right side +1 +</pre> + </td> + </tr> + <tr> + <td> + <pre class="brush: js notranslate"> +function echo(name, num) { + console.log("Evaluating the " + name + " side"); + return num; +} +// べき乗演算子 (**) の場合 +console.log(echo("left", 2) ** echo("middle", 3) ** echo("right", 2)); +</pre> + </td> + <td> + <pre class="notranslate"> +Evaluating the left side +Evaluating the middle side +Evaluating the right side +512 +</pre> + </td> + </tr> + <tr> + <td> + <pre class="brush: js notranslate"> +function echo(name, num) { + console.log("Evaluating the " + name + " side"); + return num; +} +// 左と中央の間のべき乗を括弧で囲んだ場合 +console.log((echo("left", 2) ** echo("middle", 3)) ** echo("right", 2));</pre> + </td> + <td> + <pre class="notranslate"> +Evaluating the left side +Evaluating the middle side +Evaluating the right side +64</pre> + </td> + </tr> + </tbody> +</table> + +<p>上記のコードを見てください。<code>6 / 3 / 2</code> は、除算が左結合なので <code>(6 / 3) / 2</code> と同じになります。一方で、べき乗は右結合なので、<code>2 ** 3 ** 2</code> は <code>2 ** (3 ** 2)</code> と同じになります。したがって、<code>(2 ** 3) ** 2</code> とすると上記の表にある通り、演算順序が変わって結果が 64 になります。</p> + +<p>優先順位は結合度よりも優先されることを忘れないでください。そのため、割り算とべき乗を交ぜた場合、べき乗は割り算よりも先に計算されます。例えば <code>2 ** 3 / 3 ** 2</code> の結果は 0.8888888888888888 となります。これは <code>(2 ** 3) / (3 ** 2)</code> と同じだからです。</p> + +<h3 id="グループ化と短絡の注意">グループ化と短絡の注意</h3> + +<p>下記の表では、<strong>グループ化</strong>が最上位の優先順位を持つものとして挙げられています。しかし、特に短絡が発生する場合は、グループ化記号 <code>( … )</code> の中の式が最初に評価されるとは限りません。</p> + +<p>短絡は、条件付き評価を表す用語です。例えば、<code>a && (b + c)</code> という式において、<code>a</code> が {{Glossary("falsy")}} である場合、従属式である <code>(b + c)</code> は括弧で囲まれていても評価されません。この論理的分離演算子 ("OR") は「短絡的」といえるでしょう。論理的分離演算子の他にも、ほかに短絡が発生する演算子には、論理的結合 ("AND") 演算子、Null 合体演算子、オプションチェーン演算子、条件演算子があります。いかに例を示します。</p> + +<pre class="brush: js notranslate">a || (b * c); // `a` を最初に評価し、`a` が "truthy" であれば `a` を出力 +a && (b < c); // `a` を最初に評価し、`a` が "falsy" であれば `a` を出力 +a ?? (b || c); // `a` を最初に評価し、`a` が `null` または `undefined` でなければ `a` を出力 +a?.b.c; // `a` を最初に評価し、then produce `a` if `a` is `null` or `undefined` +</pre> + +<h2 id="Examples" name="Examples">例</h2> + +<pre class="brush: js notranslate">3 > 2 && 2 > 1 +// returns true + +3 > 2 > 1 +// 結果は false となる。3 > 2 は true であり、true は +// 不等号で 1 に変換されるため、true > 1 は 1 > 1 となり、 +// false となる。(3 > 2) > 1 のように括弧を付けると明確になる。 +</pre> + +<h2 id="Table" name="Table">一覧表</h2> + +<p>以下の表は優先順位の最も高いもの (21) から最も低いもの (1) の順に並べられています。</p> + +<table class="fullwidth-table"> + <tbody> + <tr> + <th>優先順位</th> + <th>演算子の種類</th> + <th>結合性</th> + <th>演算子</th> + </tr> + <tr> + <td>21</td> + <td>{{jsxref("Operators/Grouping", "グループ化", "", 1)}}</td> + <td>n/a</td> + <td><code>( … )</code></td> + </tr> + <tr> + <td colspan="1" rowspan="5">20</td> + <td>{{jsxref("Operators/Property_Accessors", "メンバーへのアクセス", "#Dot_notation", 1)}}</td> + <td>左から右</td> + <td><code>… . …</code></td> + </tr> + <tr> + <td>{{jsxref("Operators/Property_Accessors", "計算値によるメンバーへのアクセス","#Bracket_notation", 1)}}</td> + <td>左から右</td> + <td><code>… [ … ]</code></td> + </tr> + <tr> + <td>{{jsxref("Operators/new","new")}} (引数リスト付き)</td> + <td>なし</td> + <td><code>new … ( … )</code></td> + </tr> + <tr> + <td><a href="/ja/docs/Web/JavaScript/Guide/Functions">関数呼び出し</a></td> + <td>左から右</td> + <td><code>… ( <var>… </var>)</code></td> + </tr> + <tr> + <td><a href="/ja/docs/Web/JavaScript/Reference/Operators/Optional_chaining">オプショナルチェイニング</a></td> + <td>左から右</td> + <td><code>?.</code></td> + </tr> + <tr> + <td rowspan="1">19</td> + <td>{{jsxref("Operators/new","new")}} (引数リストなし)</td> + <td>右から左</td> + <td><code>new …</code></td> + </tr> + <tr> + <td rowspan="2">18</td> + <td>{{jsxref("Operators/Arithmetic_Operators","後置インクリメント","#Increment", 1)}}</td> + <td colspan="1" rowspan="2">なし</td> + <td><code>… ++</code></td> + </tr> + <tr> + <td>{{jsxref("Operators/Arithmetic_Operators","後置デクリメント","#Decrement", 1)}}</td> + <td><code>… --</code></td> + </tr> + <tr> + <td colspan="1" rowspan="10">17</td> + <td><a href="/ja/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Logical_NOT">論理 NOT</a></td> + <td colspan="1" rowspan="10">右から左</td> + <td><code>! …</code></td> + </tr> + <tr> + <td><a href="/ja/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_NOT">ビットごとの NOT</a></td> + <td><code>~ …</code></td> + </tr> + <tr> + <td><a href="/ja/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Unary_plus">単項 +</a></td> + <td><code>+ …</code></td> + </tr> + <tr> + <td><a href="/ja/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Unary_negation">単項 -</a></td> + <td><code>- …</code></td> + </tr> + <tr> + <td><a href="/ja/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Increment">前置インクリメント</a></td> + <td><code>++ …</code></td> + </tr> + <tr> + <td><a href="/ja/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Decrement">前置デクリメント</a></td> + <td><code>-- …</code></td> + </tr> + <tr> + <td>{{jsxref("Operators/typeof", "typeof")}}</td> + <td><code>typeof …</code></td> + </tr> + <tr> + <td>{{jsxref("Operators/void", "void")}}</td> + <td><code>void …</code></td> + </tr> + <tr> + <td>{{jsxref("Operators/delete", "delete")}}</td> + <td><code>delete …</code></td> + </tr> + <tr> + <td>{{jsxref("Operators/await", "await")}}</td> + <td><code>await …</code></td> + </tr> + <tr> + <td>16</td> + <td><a href="/ja/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Exponentiation">べき乗</a></td> + <td>右から左</td> + <td><code>… ** …</code></td> + </tr> + <tr> + <td rowspan="3">15</td> + <td><a href="/ja/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Multiplication">乗算</a></td> + <td colspan="1" rowspan="3">左から右</td> + <td><code>… * …</code></td> + </tr> + <tr> + <td><a href="/ja/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Division">除算</a></td> + <td><code>… / …</code></td> + </tr> + <tr> + <td><a href="/ja/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Remainder">剰余</a></td> + <td><code>… % …</code></td> + </tr> + <tr> + <td rowspan="2">14</td> + <td><a href="/ja/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Addition">加算</a></td> + <td colspan="1" rowspan="2">左から右</td> + <td><code>… + …</code></td> + </tr> + <tr> + <td><a href="/ja/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Subtraction">減算</a></td> + <td><code>… - …</code></td> + </tr> + <tr> + <td rowspan="3">13</td> + <td><a href="/ja/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators">左ビットシフト</a></td> + <td colspan="1" rowspan="3">左から右</td> + <td><code>… << …</code></td> + </tr> + <tr> + <td><a href="/ja/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators">右ビットシフト</a></td> + <td><code>… >> …</code></td> + </tr> + <tr> + <td><a href="/ja/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators">符号なし右ビットシフト</a></td> + <td><code>… >>> …</code></td> + </tr> + <tr> + <td rowspan="6">12</td> + <td><a href="/ja/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Less_than_operator">小なり</a></td> + <td colspan="1" rowspan="6">左から右</td> + <td><code>… < …</code></td> + </tr> + <tr> + <td><a href="/ja/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Less_than__or_equal_operator">小なりイコール</a></td> + <td><code>… <= …</code></td> + </tr> + <tr> + <td><a href="/ja/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Greater_than_operator">大なり</a></td> + <td><code>… > …</code></td> + </tr> + <tr> + <td><a href="/ja/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Greater_than_or_equal_operator">大なりイコール</a></td> + <td><code>… >= …</code></td> + </tr> + <tr> + <td>{{jsxref("Operators/in", "in")}}</td> + <td><code>… in …</code></td> + </tr> + <tr> + <td>{{jsxref("Operators/instanceof", "instanceof")}}</td> + <td><code>… instanceof …</code></td> + </tr> + <tr> + <td rowspan="4">11</td> + <td><a href="/ja/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Equality">等価</a></td> + <td colspan="1" rowspan="4">左から右</td> + <td><code>… == …</code></td> + </tr> + <tr> + <td><a href="/ja/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Inequality">不等価</a></td> + <td><code>… != …</code></td> + </tr> + <tr> + <td><a href="/ja/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Identity">厳密等価</a></td> + <td><code>… === …</code></td> + </tr> + <tr> + <td><a href="/ja/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Nonidentity">厳密不等価</a></td> + <td><code>… !== …</code></td> + </tr> + <tr> + <td>10</td> + <td><a href="/ja/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_AND">ビット単位 AND</a></td> + <td>左から右</td> + <td><code>… & …</code></td> + </tr> + <tr> + <td>9</td> + <td><a href="/ja/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_XOR">ビット単位 XOR</a></td> + <td>左から右</td> + <td><code>… ^ …</code></td> + </tr> + <tr> + <td>8</td> + <td><a href="/ja/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_OR">ビット単位 OR</a></td> + <td>左から右</td> + <td><code>… | …</code></td> + </tr> + <tr> + <td>7</td> + <td><a href="/ja/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Logical_AND">論理 AND</a></td> + <td>左から右</td> + <td><code>… && …</code></td> + </tr> + <tr> + <td>6</td> + <td><a href="/ja/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Logical_OR">論理 OR</a></td> + <td>左から右</td> + <td><code>… || …</code></td> + </tr> + <tr> + <td>5</td> + <td><a href="/ja/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator">Null 合体</a></td> + <td>left-to-right</td> + <td><code>… ?? …</code></td> + </tr> + <tr> + <td>4</td> + <td><a href="/ja/docs/Web/JavaScript/Reference/Operators/Conditional_Operator">条件</a></td> + <td>右から左</td> + <td><code>… ? … : …</code></td> + </tr> + <tr> + <td rowspan="16">3</td> + <td rowspan="16"><a href="/ja/docs/Web/JavaScript/Reference/Operators/Assignment_Operators">代入</a></td> + <td rowspan="16">右から左</td> + <td><code>… = …</code></td> + </tr> + <tr> + <td><code>… += …</code></td> + </tr> + <tr> + <td><code>… -= …</code></td> + </tr> + <tr> + <td><code>… **= …</code></td> + </tr> + <tr> + <td><code>… *= …</code></td> + </tr> + <tr> + <td><code>… /= …</code></td> + </tr> + <tr> + <td><code>… %= …</code></td> + </tr> + <tr> + <td><code>… <<= …</code></td> + </tr> + <tr> + <td><code>… >>= …</code></td> + </tr> + <tr> + <td><code>… >>>= …</code></td> + </tr> + <tr> + <td><code>… &= …</code></td> + </tr> + <tr> + <td><code>… ^= …</code></td> + </tr> + <tr> + <td><code>… |= …</code></td> + </tr> + <tr> + <td><code>… &&= …</code></td> + </tr> + <tr> + <td><code>… ||= …</code></td> + </tr> + <tr> + <td><code>… ??= …</code></td> + </tr> + <tr> + <td rowspan="2">2</td> + <td>{{jsxref("Operators/yield", "yield")}}</td> + <td colspan="1" rowspan="2">右から左</td> + <td><code>yield …</code></td> + </tr> + <tr> + <td>{{jsxref("Operators/yield*", "yield*")}}</td> + <td><code>yield* …</code></td> + </tr> + <tr> + <td>1</td> + <td><a href="/ja/docs/Web/JavaScript/Reference/Operators/Comma_Operator">カンマ / シーケンス</a></td> + <td>左から右</td> + <td><code>… , …</code></td> + </tr> + </tbody> +</table> diff --git a/files/ja/web/javascript/reference/operators/optional_chaining/index.html b/files/ja/web/javascript/reference/operators/optional_chaining/index.html new file mode 100644 index 0000000000..e7d213f8fa --- /dev/null +++ b/files/ja/web/javascript/reference/operators/optional_chaining/index.html @@ -0,0 +1,203 @@ +--- +title: Optional chaining (?.) +slug: Web/JavaScript/Reference/Operators/Optional_chaining +tags: + - Chaining + - JavaScript + - Language feature + - Operator + - Optional chaining + - Reference +translation_of: Web/JavaScript/Reference/Operators/Optional_chaining +--- +<div>{{JSSidebar("Operators")}}</div> + +<p><ruby><strong>オプショナルチェイニング</strong><rp> (</rp><rt>optional chaining</rt><rp>) </rp></ruby>演算子 <strong><code>?.</code></strong> は、接続されたオブジェクトチェーンの深くに位置するプロパティの値を、チェーン内の各参照が正しいかどうかを明示的に確認せずに読み込むことを可能にします。 <span class="seoSummary"><code>?.</code> 演算子の機能は <code>.</code> チェーン演算子と似ていますが、参照が {{glossary("nullish")}} ({{JSxRef("null")}} または {{JSxRef("undefined")}}) の場合にエラーとなるのではなく、式が短絡され <code>undefined</code> が返されるところが異なります。</span> 関数呼び出しで使用すると、与えられた関数が存在しない場合、 <code>undefined</code> を返します。</p> + +<p>これは、参照が失われた可能性のある連結されたプロパティにアクセスする時、結果的に短く単純な式になります。また、必要なプロパティの存在が保証されていない場合にオブジェクトのコンテンツを探索するのにも役立ちます。</p> + +<p>オプショナルチェイニングは、存在しないルートオブジェクトでは使用できません。<code>if (typeof a == "undefined")</code> のようなチェックを置き換えるものではありません。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-optionalchainingoperator.html", "taller")}}</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>obj</var>?.<var>prop</var> +<var>obj</var>?.[<var>expr</var>] +<em>arr</em>?.[<var>index</var>] +<var>func</var>?.(<var>args</var>) +</pre> + +<h2 id="Description" name="Description">解説</h2> + +<p>オプショナルチェイニング演算子は、参照や関数が <code>undefined</code> または <code>null</code> である可能性がある場合でも、接続されたオブジェクトの値に簡単にアクセスする手段を提供します。</p> + +<p>たとえば、入れ子構造を持つオブジェクト <code>obj</code> を考えましょう。オプショナルチェイニング演算子なしで深い入れ子になったサブプロパティにアクセスするには、次のように、各プロパティ間の参照を確認する必要があります:</p> + +<pre class="brush: js notranslate">let nestedProp = obj.first && obj.first.second;</pre> + +<p><code>obj.first.second</code> の値にアクセスする前に、 <code>obj.first</code> の値が <code>null</code> または <code>undefined</code> でないことを確認します。これにより、 <code>obj.first</code> をテストせずに直接 <code>obj.first.second</code> にアクセスしたときに起きるエラーを防ぐことができます。</p> + +<p>しかし、オプショナルチェイニング演算子 (<code>?.</code>) を使えば、<code>obj.first.second</code> にアクセスしようとする前に <code>obj.first</code> の状態を明示的にテストする必要がなくなります:</p> + +<pre class="brush: js notranslate">let nestedProp = obj.first?.second;</pre> + +<p><code>?.</code> を <code>.</code> の代わりに用いることで、 JavaScript が <code>obj.first.second</code> にアクセスしようとする前に <code>obj.first</code> が <code>null</code> または <code>undefined</code> でないことを暗黙的に確かめるようになります。<code>obj.first</code> が <code>null</code> または <code>undefined</code> であった場合、式が自動的に短絡され、 <code>undefined</code> が返ります。</p> + +<p>これは、一時的な変数が作成されないことを除き、次の式と等価です。</p> + +<pre class="brush: js notranslate">let temp = obj.first; +let nestedProp = ((temp === null || temp === undefined) ? undefined : temp.second); +</pre> + +<h3 id="Optional_chaining_with_function_calls" name="Optional_chaining_with_function_calls">関数呼び出しでオプショナルチェイニング演算子を使う</h3> + +<p>存在しない可能性がある関数の呼び出しを試行するときに、オプショナルチェイニングを使うことができます。これはたとえば、ユーザーのデバイス上で使えなかったり、実装が古かったりするために使えなかったりする可能性がある API を使うときに役立ちます。</p> + +<p>関数呼び出しでオプショナルチェイニング演算子を用いた場合、メソッドが見つからないときは自動的に <code>undefined</code> が返ります。例外はスローされません。</p> + +<pre class="brush: js notranslate">let result = someInterface.customMethod?.();</pre> + +<div class="blockIndicator note"> +<p><strong>注意:</strong> 上記のようなプロパティの関数がない場合に、<code>?.</code> を使用すると {{JSxRef("TypeError")}} 例外が発生します (<code>someInterface.customMethod is not a function</code>)。</p> +</div> + +<div class="blockIndicator note"> +<p><strong>注意:</strong> <code>someInterface</code> 自体が <code>null</code> または <code>undefined</code> の場合にも、{{JSxRef("TypeError")}} 例外が発生します (<code>someInterface is null</code>)。<code>someInterface</code> 自体が <code>null</code> または <code>undefined</code> の可能性がある場合は、次の位置にも <code>?.</code> を使用しなければなりません。<code>someInterface?.customMethod?.()</code></p> +</div> + +<h4 id="Dealing_with_optional_callbacks_or_event_handlers" name="Dealing_with_optional_callbacks_or_event_handlers">省略可能なコールバックやイベントハンドラを扱う</h4> + +<p>コールバックを使う場合や、オブジェクトからメソッドを<a href="/ja/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment">分割代入</a>を利用して取り出す場合に、存在しない値がある可能性があり、その存在を検証するまで関数として呼び出せません。その場合 <code>?.</code> を利用することで、検証の必要性を回避できます。</p> + +<pre class="brush: js notranslate">// Written as of ES2019 +function doSomething(onContent, onError) { + try { + // ... do something with the data + } + catch (err) { + if (onError) { // Testing if onError really exists + onError(err.message); + } + } +} +</pre> + +<pre class="brush: js notranslate">// Using optional chaining with function calls +function doSomething(onContent, onError) { + try { + // ... do something with the data + } + catch (err) { + onError?.(err.message); // no exception if onError is undefined + } +} +</pre> + +<h3 id="Optional_chaining_with_expressions" name="Optional_chaining_with_expressions">オプショナルチェイニング演算子を式と組み合わせて使う</h3> + +<p><a href="/ja/docs/Web/JavaScript/Reference/Operators/Property_Accessors#Bracket_notation">ブラケット表記法</a>とオプショナルチェイニング演算子を組み合わせることもできます。</p> + +<pre class="brush: js notranslate">let nestedProp = obj?.['prop' + 'Name']; +</pre> + +<h3 id="Optional_chaining_not_valid_on_the_left-hand_side_of_an_assignment" name="Optional_chaining_not_valid_on_the_left-hand_side_of_an_assignment">オプショナルチェイニング演算子は代入の左辺値では有効にならない</h3> + +<pre class="brush: js notranslate"><code>let object = {}; +object?.property = 1; // Uncaught SyntaxError: Invalid left-hand side in assignment</code></pre> + +<h3 id="オプショナルチェイニングにより配列の要素にアクセス">オプショナルチェイニングにより配列の要素にアクセス</h3> + +<pre class="brush: js notranslate">let arrayItem = arr?.[42];</pre> + +<h2 id="Examples" name="Examples">例</h2> + +<h3 id="Basic_example" name="Basic_example">基本的な例</h3> + +<p>次の例では、マップに存在しない <code>bar</code> メンバの <code>name</code> プロパティを取得しようとしています。したがって、結果は <code>undefined</code> になります。</p> + +<pre class="brush: js notranslate">let myMap = new Map(); +myMap.set("foo", {name: "baz", desc: "inga"}); + +let nameBar = myMap.get("bar")?.name;</pre> + +<h3 id="Short-circuiting_evaluation" name="Short-circuiting_evaluation">短絡評価</h3> + +<p>式と一緒にオプショナルチェイニング演算子を用いたとき、左側のオペランドが <code>null</code> または <code>undefined</code> である場合にその式は評価されなくなります。</p> + +<pre class="brush: js notranslate">let potentiallyNullObj = null; +let x = 0; +let prop = potentiallyNullObj?.[x++]; + +console.log(x); // 0 as x was not incremented +</pre> + +<h3 id="Stacking_the_optional_chaining_operator" name="Stacking_the_optional_chaining_operator">オプショナルチェイニングをつなげて使う</h3> + +<p>入れ子になったオブジェクトでは、オプショナルチェイニング演算子を何度でも使えます。</p> + +<pre class="brush: js notranslate">let customer = { + name: "Carl", + details: { + age: 82, + location: "Paradise Falls" // detailed address is unknown + } +}; +let customerCity = customer.details?.address?.city; + +// … this also works with optional chaining function call +let duration = vacations.trip?.getTime?.(); +</pre> + +<h3 id="Combining_with_the_nullish_coalescing_operator" name="Combining_with_the_nullish_coalescing_operator">Null 合体演算子と共に使う</h3> + +<p>{{JSxRef("Operators/Nullish_Coalescing_Operator", "Null 合体演算子", '', 1)}}はオプショナルチェイニングの後につけることで、存在しない値があった時、既定値をかわりに使うために利用できます。</p> + +<pre class="brush: js notranslate">let customer = { + name: "Carl", + details: { age: 82 } +}; +const customerCity = customer?.city ?? "Unknown city"; +console.log(customerCity); // Unknown city</pre> + +<h2 id="Specifications" name="Specifications">仕様</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">仕様書</th> + <th scope="col">状態</th> + <th scope="col">備考</th> + </tr> + </thead> + <tbody> + <tr> + <td><a href="https://tc39.es/proposal-optional-chaining/#sec-scope">"オプショナルチェイニング" 演算子の提案</a></td> + <td>Stage 4</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">ブラウザーの互換性</h2> + +<div> +<div class="hidden">このページの互換性一覧表は構造化データから生成されています。データに協力していただけるのであれば、 <a class="external" href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> をチェックアウトしてプルリクエストを送信してください。</div> + +<p>{{Compat("javascript.operators.optional_chaining")}}</p> +</div> + +<h3 id="Implementation_Progress" name="Implementation_Progress">実装の進捗</h3> + +<p>この機能はまだブラウザー間相互運用の安定性に達していないため、以下の表はこの機能の日々の実装状況を示しています。このデータは、 JavaScript の標準テストスイートである <a href="https://github.com/tc39/test262">Test262</a> で、該当する機能テストを毎晩のビルド、または各ブラウザーの JavaScript エンジンの最新リリースで実行することで生成されます。</p> + +<div>{{EmbedTest262ReportResultsTable("optional-chaining")}}</div> + +<h2 id="See_also" name="See_also">関連情報</h2> + +<ul> + <li>{{JSxRef("Operators/Nullish_Coalescing_Operator", "Null 合体演算子", '', 1)}}</li> + <li><a href="https://github.com/tc39/proposals">TC39 proposals</a></li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/pipeline_operator/index.html b/files/ja/web/javascript/reference/operators/pipeline_operator/index.html new file mode 100644 index 0000000000..02cbc7d0ba --- /dev/null +++ b/files/ja/web/javascript/reference/operators/pipeline_operator/index.html @@ -0,0 +1,87 @@ +--- +title: パイプライン演算子 (|>) +slug: Web/JavaScript/Reference/Operators/Pipeline_operator +tags: + - Chaining + - Experimental + - JavaScript + - Language feature + - Operator + - Pipeline + - パイプライン + - 実験的 + - 演算子 + - 言語機能 + - 連結 +translation_of: Web/JavaScript/Reference/Operators/Pipeline_operator +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>実験的なパイプライン演算子 <code>|></code> (現在はステージ 1 です) は、式の値を関数に接続します。これによって、読みやすい方法で一連の関数呼び出しを作成することができます。結果的に、単一の引数を用いた関数呼び出しの糖衣構文となり、次のように書くことができます。</p> + +<pre class="brush: js notranslate">let url = "%21" |> decodeURI;</pre> + +<p>これと等価な従来の構文は次のようになります。</p> + +<pre class="brush: js notranslate">let url = decodeURI("%21"); +</pre> + +<h2 id="Syntax" name="Syntax">構文</h2> + +<pre class="syntaxbox notranslate"><var>expression</var> |> <var>function</var> +</pre> + +<p>指定された <code><var>expression</var></code> の値が <code><var>function</var></code> に、単一の引数として渡されます。</p> + +<h3 id="Parameters" name="Parameters">引数</h3> + +<dl> + <dt><code><var>expression</var></code></dt> + <dd>任意の式です。</dd> + <dt><code><var>function</var></code></dt> + <dd>任意の関数です。</dd> +</dl> + +<h2 id="Examples" name="Examples">例</h2> + +<h3 id="Chaining_function_calls" name="Chaining_function_calls">関数呼び出しの連結</h3> + +<p>パイプライン演算子は、複数の関数の連結を読みやすくすることができます。</p> + +<pre class="brush: js notranslate">const double = (n) => n * 2; +const increment = (n) => n + 1; + +// パイプライン演算子なし +double(increment(double(double(5)))); // 42 + +// パイプライン演算子あり +5 |> double |> double |> increment |> double; // 42 +</pre> + +<h2 id="Specifications" name="Specifications">仕様</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">仕様書</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('Pipeline operator', '#sec-intro', 'Pipeline operator')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">ブラウザー実装状況</h2> + + + +<p>{{Compat("javascript.operators.pipeline")}}</p> + +<h2 id="See_also" name="See_also">関連情報</h2> + +<ul> + <li><a href="https://github.com/tc39/proposal-pipeline-operator">Github - Proposal-pipeline-operator</a></li> + <li><a href="https://github.com/tc39/proposals">TC39 proposals</a></li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/property_accessors/index.html b/files/ja/web/javascript/reference/operators/property_accessors/index.html new file mode 100644 index 0000000000..6683586246 --- /dev/null +++ b/files/ja/web/javascript/reference/operators/property_accessors/index.html @@ -0,0 +1,155 @@ +--- +title: プロパティアクセサー +slug: Web/JavaScript/Reference/Operators/Property_Accessors +tags: + - JavaScript + - Operator + - Reference + - 演算子 +translation_of: Web/JavaScript/Reference/Operators/Property_Accessors +--- +<div>{{jsSidebar("Operators")}}</div> + +<p><strong>プロパティアクセサー</strong>はオブジェクトのプロパティへのアクセスを提供するもので、ドット表記法またはブラケット表記法を使用します。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-propertyaccessors.html")}}</div> + +<p class="hidden">このデモのソースファイルは GitHub リポジトリに格納されています。デモプロジェクトに協力したい場合は、 <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> をクローンしてプルリクエストを送信してください。</p> + +<h2 id="Syntax" name="Syntax">構文</h2> + +<pre class="syntaxbox">object.property +object['property'] +</pre> + +<h2 id="Description" name="Description">解説</h2> + +<p>オブジェクトは実際には<em>連想配列</em> (別名 <em>map</em>、 <em>dictionary</em>、 <em>hash</em>、 <em>lookup table</em>) とみなすことができます。この配列における<em>キー</em>はオブジェクトのプロパティ名です。一般的に、オブジェクトのプロパティについて説明する際には、プロパティとメソッドを区別します。しかし、プロパティとメソッドの区別は慣習的なものにすぎません。メソッドは単なるプロパティであり、言わば、例えば値として {{jsxref("Function")}} オブジェクトのインスタンスへの参照を持っているものです。</p> + +<p>プロパティにアクセスするには、ドット表記法とブラケット表記法の2通りがあります。</p> + +<h3 id="Dot_notation" name="Dot_notation">ドット表記法</h3> + +<pre class="brush: js">get = object.property; +object.property = set; +</pre> + +<p><code>property</code> は有効な JavaScript 識別子である必要があります。例えば <code>object.$1</code> は有効ですが、 <code>object.1</code> は有効ではありません。</p> + +<pre class="brush: js">document.createElement('pre'); +</pre> + +<p>ここでは、 <code>document</code> から "createElement" という名前のメソッドが検索され、呼び出されます。</p> + +<p>指数や小数点を持たない数値リテラルにメソッドを使用する場合、メソッド呼び出しをするドットの前に{{glossary("Whitespace", "ホワイトスペース")}}を入れることで、ドットが小数点とみなされることを防ぐことができます。</p> + +<pre class="brush: js">77 .toExponential(); +// or +77 +.toExponential(); +// or +(77).toExponential(); +// or +77..toExponential(); +// or +77.0.toExponential(); +// because 77. === 77.0, no ambiguity</pre> + +<h3 id="Bracket_notation" name="Bracket_notation">ブラケット表記法</h3> + +<pre class="brush: js">get = object[property_name]; +object[property_name] = set; +</pre> + +<p><code>property_name</code> は文字列または{{glossary("Symbol", "シンボル")}}です。この文字列は有効な識別子である必要はなく、任意の値、例えば "<code>1foo</code>", "<code>!bar!</code>", または "<code> </code>" (空白) であっても構いません。</p> + +<pre class="brush: js">document['createElement']('pre'); +</pre> + +<p>これは前の例とまったく同じです。</p> + +<p>ブラケット表記法の前には空白を入れることができます。</p> + +<pre class="brush: js">document ['createElement']('pre');</pre> + +<h3 id="Property_names" name="Property_names">プロパティ名</h3> + +<p>プロパティ名は文字列または{{glossary("Symbol", "シンボル")}}です。それ以外の値は、数値を含めて、文字列へ強制変換されます。</p> + +<pre class="brush: js">var object = {}; +object['1'] = 'value'; +console.log(object[1]); +</pre> + +<p>これは、 <code>1</code> が <code>'1'</code> に強制変換されるので、 "value" を出力します。</p> + +<pre class="brush: js">var foo = {unique_prop: 1}, bar = {unique_prop: 2}, object = {}; +object[foo] = 'value'; +console.log(object[bar]); +</pre> + +<p><code>foo</code> と <code>bar</code> は同じ文字列に変換されるので、こちらも "value" を出力します。 <a href="/ja/docs/Mozilla/Projects/SpiderMonkey">SpiderMonkey</a> JavaScript エンジンでは、この文字列は "<code>[object Object]</code>" となるでしょう。</p> + +<h3 id="Method_binding" name="Method_binding">メソッドのバインド</h3> + +<p>メソッドはそのメソッドが所属するオブジェクトにバインドされているわけではありません。特に、 <code>this</code> はメソッド内で固定されていません。つまり、 <code>this</code> は必ずしもそのメソッドを含んでいるオブジェクトを参照しているとは限りません。 <code>this</code> は関数呼び出し時に「渡される」ものです。<a href="/ja/docs/JavaScript/Reference/Operators/this#Method_binding">メソッドのバインド</a>を参照してください。</p> + +<h3 id="Note_on_eval" name="Note_on_eval"><code>eval</code> におけるメモ</h3> + +<p>JavaScript 初心者はしばしば、代わりにブラケット表記法を使えるところで {{jsxref("eval", "eval()")}} を使用してしまう間違いを犯します。例えば、以下のような構文がたくさんのスクリプトで見られます。</p> + +<pre class="brush: js">x = eval('document.forms.form_name.elements.' + strFormControl + '.value'); +</pre> + +<p><code>eval()</code> は低速であり、可能な限り避けるべきです。また、 <code>strFormControl</code> は ID を必要としますが、フォームコントロールの名前と ID は必須ではありません。代わりにブラケット表記法を使った方が良いでしょう。</p> + +<pre class="brush: js">x = document.forms['form_name'].elements[strFormControl].value; +</pre> + +<h2 id="Specifications" name="Specifications">仕様書</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">仕様書</th> + <th scope="col">状態</th> + <th scope="col">備考</th> + </tr> + </tbody> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-property-accessors', 'Property Accessors')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-property-accessors', 'Property Accessors')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-11.2.1', 'Property Accessors')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES1', '#sec-11.2.1', 'Property Accessors')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>初回定義。JavaScript 1.0 で実装。</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">ブラウザーの互換性</h2> + +<div class="hidden">このページの互換性一覧表は構造化データから生成されています。データに協力していただけるのであれば、 <a class="external" href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> をチェックアウトしてプルリクエストを送信してください。</div> + +<p>{{Compat("javascript.operators.property_accessors")}}</p> + +<h2 id="See_also" name="See_also">関連情報</h2> + +<ul> + <li>{{jsxref("Object")}}</li> + <li>{{jsxref("Object.defineProperty()")}}</li> + <li><a href="/ja/docs/Web/JavaScript/Reference/Operators/Optional_chaining">Optional chaining</a></li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/remainder/index.html b/files/ja/web/javascript/reference/operators/remainder/index.html new file mode 100644 index 0000000000..7bc17ee93d --- /dev/null +++ b/files/ja/web/javascript/reference/operators/remainder/index.html @@ -0,0 +1,78 @@ +--- +title: 剰余 (%) +slug: Web/JavaScript/Reference/Operators/Remainder +tags: + - JavaScript + - Language feature + - Operator + - Reference +translation_of: Web/JavaScript/Reference/Operators/Remainder +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>剰余演算子 (<code>%</code>) は、1つ目のオペランドが2つ目のオペランドで除算されたときに残った剰余を返します。 これは常に配当のサインを取ります。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-remainder.html")}}</div> + +<div></div> + + + +<h2 id="構文">構文</h2> + +<pre class="syntaxbox notranslate"><strong>Operator:</strong> <var>var1</var> % <var>var2</var> +</pre> + +<h2 id="例">例</h2> + +<h3 id="正の値の剰余">正の値の剰余</h3> + +<pre class="brush: js notranslate"> 12 % 5 // 2 + 1 % -2 // 1 + 1 % 2 // 1 + 2 % 3 // 2 +5.5 % 2 // 1.5 +</pre> + +<h3 id="負の値の剰余">負の値の剰余</h3> + +<pre class="brush: js notranslate">-12 % 5 // -2 +-1 % 2 // -1 +-4 % 2 // -0</pre> + +<h3 id="NaNの剰余">NaNの剰余</h3> + +<pre class="brush: js notranslate">NaN % 2 // NaN</pre> + +<h2 id="仕様">仕様</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">仕様</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-multiplicative-operators', 'Remainder operator')}}</td> + </tr> + </tbody> +</table> + +<h2 id="ブラウザーの互換性">ブラウザーの互換性</h2> + + + +<p>{{Compat("javascript.operators.remainder")}}</p> + +<h2 id="関連項目">関連項目</h2> + +<ul> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Addition">加算演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Subtraction">減算演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Multiplication">乗算演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Division">除算演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Exponentiation">べき乗演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Increment">インクリメント演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Decrement">デクリメント演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Unary_negation">単項マイナス演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Unary_plus">単項プラス演算子</a></li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/remainder_assignment/index.html b/files/ja/web/javascript/reference/operators/remainder_assignment/index.html new file mode 100644 index 0000000000..ab7d348b8b --- /dev/null +++ b/files/ja/web/javascript/reference/operators/remainder_assignment/index.html @@ -0,0 +1,62 @@ +--- +title: 剰余代入 (%=) +slug: Web/JavaScript/Reference/Operators/Remainder_assignment +tags: + - Assignment operator + - JavaScript + - Language feature + - Operator + - Reference +translation_of: Web/JavaScript/Reference/Operators/Remainder_assignment +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>剰余代入演算子 (<code>%=</code>) は、変数を右辺のオペランドの値で除算し、剰余を変数に代入します。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-remainder-assignment.html")}}</div> + +<div></div> + + + +<h2 id="構文">構文</h2> + +<pre class="syntaxbox notranslate"><strong>Operator:</strong> x %= y +<strong>Meaning:</strong> x = x % y</pre> + +<h2 id="例">例</h2> + +<h3 id="剰余代入の使用">剰余代入の使用</h3> + +<pre class="brush: js notranslate">// 以下の変数を想定 +// bar = 5 + +bar %= 2 // 1 +bar %= 'foo' // NaN +bar %= 0 // NaN</pre> + +<h2 id="仕様">仕様</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">仕様</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-assignment-operators', 'Assignment operators')}}</td> + </tr> + </tbody> +</table> + +<h2 id="ブラウザーの互換性">ブラウザーの互換性</h2> + + + +<p>{{Compat("javascript.operators.remainder_assignment")}}</p> + +<h2 id="関連項目">関連項目</h2> + +<ul> + <li><a href="/docs/Web/JavaScript/Guide/Expressions_and_Operators#Assignment">代入演算子</a></li> + <li><a href="/docs/Web/JavaScript/Reference/Operators/Remainder">剰余演算子</a></li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/right_shift/index.html b/files/ja/web/javascript/reference/operators/right_shift/index.html new file mode 100644 index 0000000000..3cd729c321 --- /dev/null +++ b/files/ja/web/javascript/reference/operators/right_shift/index.html @@ -0,0 +1,79 @@ +--- +title: 右シフト (>>) +slug: Web/JavaScript/Reference/Operators/Right_shift +tags: + - Bitwise operator + - JavaScript + - Language feature + - Operator + - Reference + - 演算子 + - 言語機能 +translation_of: Web/JavaScript/Reference/Operators/Right_shift +--- +<div>{{jsSidebar("Operators")}}</div> + +<p><strong>右シフト演算子 (<code>>></code>)</strong> (ゼロ埋め右シフト) は、1つ目のオペランドを指定されたビット数だけ右にずらします。右にずらしてあふれたビットは廃棄されます。最も左のビットをコピーしながらずれて入ります。最も左のビットが以前の最も左のビットと同じになるため、符号ビット (最も左のビット) は変化しません。よって「符号維持」という名前です。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-right-shift.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"><code><var>a</var> >> <var>b</var></code> +</pre> + +<h2 id="Description" name="Description">解説</h2> + +<p>この演算子は、1つ目のオペランドを指定されたビット数だけ右にずらします。右にずらしてあふれたビットは廃棄されます。最も左のビットをコピーしながらずれて入ります。最も左のビットが以前の最も左のビットと同じになるため、符号ビット (最も左のビット) は変化しません。よって「符号維持」という名前です。</p> + +<p>例えば、 <code>9 >>> 2</code> は 2 となります。</p> + +<pre class="brush: js notranslate">. 9 (10進数): 00000000000000000000000000001001 (2進数) + -------------------------------- +9 >>> 2 (10進数): 00000000000000000000000000000010 (2進数) = 2 (10進数) +</pre> + +<p>同様に、 <code>-9 >> 2</code> は符号が保存されるため、 <code>-3</code> になります。</p> + +<pre class="brush: js notranslate">. -9 (10進数): 11111111111111111111111111110111 (2進数) + -------------------------------- +-9 >> 2 (10進数): 11111111111111111111111111111101 (2進数) = -3 (10進数) +</pre> + +<h2 id="Examples" name="Examples">例</h2> + +<h3 id="Using_right_shift" name="Using_right_shift">右シフトの使用</h3> + +<pre class="brush: js notranslate"> 9 >> 2; // 2 +-9 >> 2; // -3 +</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-bitwise-shift-operators', 'Bitwise Shift Operators')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">ブラウザーの互換性</h2> + +<div class="hidden">このページの互換性一覧表は構造化データから生成されています。データに協力していただけるのであれば、 <a class="external" href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> をチェックアウトしてプルリクエストを送信してください。</div> + +<p>{{Compat("javascript.operators.right_shift")}}</p> + +<h2 id="See_also" name="See_also">関連情報</h2> + +<ul> + <li><a href="/ja/docs/Web/JavaScript/Guide/Expressions_and_Operators#Bitwise">JavaScript ガイドのビット毎演算子</a></li> + <li><a href="/ja/docs/Web/JavaScript/Reference/Operators/Right_shift_assignment">右シフト代入演算子</a></li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/right_shift_assignment/index.html b/files/ja/web/javascript/reference/operators/right_shift_assignment/index.html new file mode 100644 index 0000000000..6ff0bb1cba --- /dev/null +++ b/files/ja/web/javascript/reference/operators/right_shift_assignment/index.html @@ -0,0 +1,61 @@ +--- +title: 右シフト代入 (>>=) +slug: Web/JavaScript/Reference/Operators/Right_shift_assignment +tags: + - Assignment operator + - JavaScript + - Language feature + - Operator + - Reference +translation_of: Web/JavaScript/Reference/Operators/Right_shift_assignment +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>右シフト代入演算子 (<code>>>=</code>) は、指定された量のビットを右に移動し、結果を変数に代入します。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-right-shift-assignment.html")}}</div> + +<div></div> + + + +<h2 id="構文">構文</h2> + +<pre class="syntaxbox notranslate"><strong>Operator:</strong> x >>= y +<strong>Meaning:</strong> x = x >> y</pre> + +<h2 id="例">例</h2> + +<h3 id="右シフト代入の使用">右シフト代入の使用</h3> + +<pre class="brush: js notranslate">let a = 5; // (00000000000000000000000000000101) +a >>= 2; // 1 (00000000000000000000000000000001) + +let b = -5; // (-00000000000000000000000000000101) +b >>= 2; // -2 (-00000000000000000000000000000010)</pre> + +<h2 id="仕様">仕様</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">仕様</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-assignment-operators', 'Assignment operators')}}</td> + </tr> + </tbody> +</table> + +<h2 id="ブラウザー実装状況">ブラウザー実装状況</h2> + + + +<p>{{Compat("javascript.operators.right_shift_assignment")}}</p> + +<h2 id="関連項目">関連項目</h2> + +<ul> + <li><a href="/docs/Web/JavaScript/Guide/Expressions_and_Operators#Assignment">代入演算子</a></li> + <li><a href="/docs/Web/JavaScript/Reference/Operators/Right_shift">右シフト演算子</a></li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/special/index.html b/files/ja/web/javascript/reference/operators/special/index.html new file mode 100644 index 0000000000..cb220a008d --- /dev/null +++ b/files/ja/web/javascript/reference/operators/special/index.html @@ -0,0 +1,5 @@ +--- +title: Special +slug: Web/JavaScript/Reference/Operators/Special +--- +This page was auto-generated because a user created a sub-page to this page. diff --git a/files/ja/web/javascript/reference/operators/special_operators/index.html b/files/ja/web/javascript/reference/operators/special_operators/index.html new file mode 100644 index 0000000000..febf3ac3d6 --- /dev/null +++ b/files/ja/web/javascript/reference/operators/special_operators/index.html @@ -0,0 +1,5 @@ +--- +title: Special Operators +slug: Web/JavaScript/Reference/Operators/Special_Operators +--- +This page was auto-generated because a user created a sub-page to this page. diff --git a/files/ja/web/javascript/reference/operators/spread_syntax/index.html b/files/ja/web/javascript/reference/operators/spread_syntax/index.html new file mode 100644 index 0000000000..d433ed2b34 --- /dev/null +++ b/files/ja/web/javascript/reference/operators/spread_syntax/index.html @@ -0,0 +1,258 @@ +--- +title: スプレッド構文 +slug: Web/JavaScript/Reference/Operators/Spread_syntax +tags: + - ECMAScript 2015 + - Iterator + - JavaScript + - Language feature + - Reference + - イテレーター + - 言語機能 +translation_of: Web/JavaScript/Reference/Operators/Spread_syntax +--- +<div>{{jsSidebar("Operators")}}</div> + +<p><strong>スプレッド構文</strong> (<code>...</code>) を使うと、配列式や文字列などの反復可能オブジェクトを、0 個以上の引数 (関数呼び出しの場合) や要素 (配列リテラルの場合) を期待された場所で展開したり、オブジェクト式を、0 個以上のキーと値のペア (オブジェクトリテラルの場合) を期待された場所で展開したりすることができます。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-spreadsyntax.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> + +<p>関数呼び出しの場合:</p> + +<pre class="syntaxbox notranslate"><var>myFunction</var>(...<var>iterableObj</var>); +</pre> + +<p>配列リテラルや文字列の場合:</p> + +<pre class="syntaxbox notranslate">[...<var>iterableObj</var>, '4', 'five', 6];</pre> + +<p>オブジェクトリテラルの場合 (ECMAScript 2018 の新機能)</p> + +<pre class="syntaxbox notranslate">let <var>objClone</var> = { ...<var>obj</var> };</pre> + +<h2 id="Rest_syntax_parameters" name="Rest_syntax_parameters">残余構文 (引数)</h2> + +<p>残余構文はスプレッド構文と外見がよく似ていますが、配列やオブジェクトの<em>分割代入</em>に使われます。</p> + +<p>こちらはスプレッド構文とは逆の働きといえます。スプレッド構文が要素を展開するのに対して、残余構文は複数の要素を集約して 1 つのオブジェクトに「濃縮」します。{{jsxref("Functions/rest_parameters", "残余引数", "", 1)}}を参照してください。</p> + +<h2 id="Examples" name="Examples">例</h2> + +<h3 id="Spread_in_function_calls" name="Spread_in_function_calls">関数呼び出しでの展開</h3> + +<h4 id="Replace_apply" name="Replace_apply">apply() を置き換える</h4> + +<p>配列の要素を引数にして関数を呼び出すには {{jsxref("Function.prototype.apply()")}} を使うのが一般的です。</p> + +<pre class="brush: js notranslate">function myFunction(x, y, z) { } +let args = [0, 1, 2]; +myFunction.apply(null, args);</pre> + +<p>スプレッド構文を使うと、上のコードは次のように書くことができます。</p> + +<pre class="brush: js notranslate">function myFunction(x, y, z) { } +let args = [0, 1, 2]; +myFunction(...args);</pre> + +<p>スプレッド構文は、引数の何番目でも使えます。また、複数回使えます。</p> + +<pre class="brush: js notranslate">function myFunction(v, w, x, y, z) { } +let args = [0, 1]; +myFunction(-1, ...args, 2, ...[3]);</pre> + +<h4 id="Apply_for_new" name="Apply_for_new">new 演算子の適用</h4> + +<p>{{jsxref("Operators/new", "new")}} によってコンストラクターを呼び出すとき、配列と <code>apply()</code> を<strong>直接</strong>使用することはできません (<code>apply()</code> は <code>[[Call]]</code> を実行するのであり <code>[[Construct]]</code> ではない)。ただし、配列はスプレッド構文のおかげで簡単に <code>new</code> を使用することができます。</p> + +<pre class="brush: js notranslate">let dateFields = [1970, 0, 1]; // 1 Jan 1970 +let d = new Date(...dateFields); +</pre> + +<p>スプレッド構文を使わずに同じ結果を得るには、専用の関数を使う<strong>間接的</strong>な手段を取らざるをえません。</p> + +<pre class="brush: js notranslate">function applyAndNew(constructor, args) { + function partial () { + return constructor.apply(this, args); + }; + if (typeof constructor.prototype === "object") { + partial.prototype = Object.create(constructor.prototype); + } + return partial; +} + + +function myConstructor () { + console.log("arguments.length: " + arguments.length); + console.log(arguments); + this.prop1="val1"; + this.prop2="val2"; +}; + +let myArguments = ["hi", "how", "are", "you", "mr", null]; +let myConstructorWithArguments = applyAndNew(myConstructor, myArguments); + +console.log(new myConstructorWithArguments); +// (internal log of myConstructor): arguments.length: 6 +// (internal log of myConstructor): ["hi", "how", "are", "you", "mr", null] +// (log of "new myConstructorWithArguments"): {prop1: "val1", prop2: "val2"}</pre> + +<h3 id="Spread_in_array_literals" name="Spread_in_array_literals">配列リテラルでのスプレッド構文</h3> + +<h4 id="A_more_powerful_array_literal" name="A_more_powerful_array_literal">より強力な配列リテラル</h4> + +<p>スプレッド構文を使用しない場合、既存の配列を一部として使用して新しい配列を作成するには、配列リテラル構文は十分ではなく、{{jsxref("Array.prototype.push", "push()")}}, {{jsxref("Array.prototype.splice", "splice()")}}, {{jsxref("Array.prototype.concat", "concat()")}} などを組み合わせて使う高圧的なコードを使用しなければなりません。</p> + +<pre class="brush: js notranslate">let parts = ['shoulders', 'knees']; +let lyrics = ['head', ...parts, 'and', 'toes']; +// ["head", "shoulders", "knees", "and", "toes"] +</pre> + +<p>関数の引数と同様に、<code>...</code> は配列リテラルのどこでも、何回でも使えます。</p> + +<h4 id="Copy_an_array" name="Copy_an_array">配列を複製する</h4> + +<pre class="brush: js notranslate">let arr = [1, 2, 3]; +let arr2 = [...arr]; // arr.slice() のような動きです + +arr2.push(4); +// arr2 は [1, 2, 3, 4] になります +// arr は変更されません +</pre> + +<div class="blockIndicator note"> +<p><strong>メモ:</strong> コピーは 1 段階の深さで行われます。そのため、次の例のような多次元配列のようなオブジェクトをコピーする場合には適さないでしょう。({{jsxref("Object.assign()")}} についても同じことが言えます。)</p> + +<pre class="brush: js example-bad notranslate">let a = [[1], [2], [3]]; +let b = [...a]; + +b.shift().shift(); +// 1 + +// あらら、配列 'a' も影響を受けちゃった。 +a +// [[], [2], [3]] +</pre> +</div> + +<h4 id="A_better_way_to_concatenate_arrays" name="A_better_way_to_concatenate_arrays">配列を連結するより良い方法</h4> + +<p>ある配列を既存の配列の末尾に連結するには、{{jsxref("Array.prototype.concat()")}} がよく使われます。スプレッド構文を使用しないと、これは次のように行われます。</p> + +<pre class="brush: js notranslate">let arr1 = [0, 1, 2]; +let arr2 = [3, 4, 5]; + +// arr2 のすべての要素を arr1 に追加する +arr1 = arr1.concat(arr2);</pre> + +<p>スプレッド構文を使うと、次のように書けます。</p> + +<pre class="brush: js notranslate">let arr1 = [0, 1, 2]; +let arr2 = [3, 4, 5]; + +arr1 = [...arr1, ...arr2]; +// arr1 は [0, 1, 2, 3, 4, 5] となる +// 注: これ以外に const を使用すると、TypeError (invalid assignment) が発生します +</pre> + +<p>{{jsxref("Array.prototype.unshift()")}} は、値の配列を既存の配列の先頭に挿入するためによく使われます。スプレッド構文を使用しないと、これは次のように行われます。</p> + +<pre class="brush: js notranslate">let arr1 = [0, 1, 2]; +let arr2 = [3, 4, 5]; + +// arr2 のすべての要素を arr1 へ移植します +Array.prototype.unshift.apply(arr1, arr2) + +// arr1 is now [3, 4, 5, 0, 1, 2]</pre> + +<p>スプレッド構文を使うと、次のようになります。</p> + +<pre class="brush: js notranslate">let arr1 = [0, 1, 2]; +let arr2 = [3, 4, 5]; + +arr1 = [...arr2, ...arr1]; +// arr1 is now [3, 4, 5, 0, 1, 2] +</pre> + +<div class="blockIndicator note"> +<p><strong>メモ:</strong> <code>unshift()</code> とは異なり、これは新しい <code>arr1</code> を生成しており、その場では元の <code>arr1</code> を変更しません</p> +</div> + +<h3 id="Spread_in_object_literals" name="Spread_in_object_literals">Object リテラルで使う</h3> + +<p><a href="https://github.com/tc39/proposal-object-rest-spread">Rest/Spread Properties for ECMAScript</a> proposal (ES2018) では、{{jsxref("Operators/Object_initializer", "オブジェクトリテラル", 1)}}でのスプレッド構文が追加されています。スプレッド構文の対象となるオブジェクトの列挙可能なプロパティを、新しいオブジェクトにコピーします。</p> + +<p>浅いコピー (プロトタイプを除く) の作成や、マージしたオブジェクトの作成が {{jsxref("Object.assign()")}} を使うよりも短いコードで書けます。</p> + +<pre class="brush: js notranslate">let obj1 = { foo: 'bar', x: 42 }; +let obj2 = { foo: 'baz', y: 13 }; + +let clonedObj = { ...obj1 }; +// Object { foo: "bar", x: 42 } + +let mergedObj = { ...obj1, ...obj2 }; +// Object { foo: "baz", x: 42, y: 13 }</pre> + +<p>{{jsxref("Object.assign()")}} は{{jsxref("Functions/set", "セッター")}}を起動しますが、スプレッド構文は起動しないことに注意してください。</p> + +<p>スプレッド構文は {{jsxref("Object.assign()")}} 関数を置き換えたり模倣することはできないことに注意してください。</p> + +<pre class="brush: js notranslate">let obj1 = { foo: 'bar', x: 42 }; +let obj2 = { foo: 'baz', y: 13 }; +const merge = ( ...objects ) => ( { ...objects } ); + +let mergedObj1 = merge (obj1, obj2); +// Object { 0: { foo: 'bar', x: 42 }, 1: { foo: 'baz', y: 13 } } + +let mergedObj2 = merge ({}, obj1, obj2); +// Object { 0: {}, 1: { foo: 'bar', x: 42 }, 2: { foo: 'baz', y: 13 } }</pre> + +<p>上記の例では、スプレッド構文は期待通りに動作しません。残りの引数があるため、引数の<em>配列</em>がオブジェクトリテラルにとして展開されます。</p> + +<h3 id="Only_for_iterables" name="Only_for_iterables">反復可能オブジェクトにのみ利用可能</h3> + +<p>オブジェクト自体は反復可能ではありませんが、配列の中で使用したり、<code>map()</code>, <code>reduce()</code>, <code>assign()</code> などの反復関数と共に使用したりすることで反復可能になります。2 つのオブジェクトをスプレッド演算子で結合する場合は、結合時に別の反復処理関数を使用することを前提としています。</p> + +<p>スプレッド構文 (スプレッドプロパティの場合を除く) は、<a href="/ja/docs/Web/JavaScript/Reference/Global_Objects/Symbol/iterator">反復可能</a>オブジェクトにのみ適用できます。</p> + +<pre class="brush: js notranslate">let obj = {'key1': 'value1'}; +let array = [...obj]; // TypeError: obj is not iterable +</pre> + +<h3 id="Spread_with_many_values" name="Spread_with_many_values">大量の値を展開する場合</h3> + +<p>JavaScript エンジンには、引数の個数に上限があります。関数呼び出しでのスプレッド構文では、引数の個数がその上限を超えてしまう可能性に留意してください。詳細は {{jsxref("Function.prototype.apply", "apply()")}} のページを参照してください。</p> + +<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-initializer', 'Array initializer')}}</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-object-initializer', 'Object initializer')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">ブラウザーの互換性</h2> + +<div class="hidden">このページの互換性一覧表は構造化データから生成されています。データに協力していただけるのであれば、<a class="external" href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> をチェックアウトしてプルリクエストを送信してください。</div> + +<p>{{Compat("javascript.operators.spread")}}</p> + +<h2 id="See_also" name="See_also">関連情報</h2> + +<ul> + <li>{{jsxref("Functions/rest_parameters", "残余引数", "", 1)}} (also ‘<code>...</code>’)</li> + <li>{{jsxref("Function.prototype.apply()")}} (also ‘<code>...</code>’)</li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/strict_equality/index.html b/files/ja/web/javascript/reference/operators/strict_equality/index.html new file mode 100644 index 0000000000..a3bc1e89d7 --- /dev/null +++ b/files/ja/web/javascript/reference/operators/strict_equality/index.html @@ -0,0 +1,108 @@ +--- +title: 厳密等価 (===) +slug: Web/JavaScript/Reference/Operators/Strict_equality +tags: + - JavaScript + - Language feature + - Operator + - Reference + - 演算子 + - 言語機能 +translation_of: Web/JavaScript/Reference/Operators/Strict_equality +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>厳密等価演算子 (<code>===</code>) は、二つのオペランドが等しいことを検査し、論理値で結果を返します <a href="/ja/docs/Web/JavaScript/Reference/Operators/Equality">等価</a>演算子とは異なり、厳密等価演算子はオペランドの型が異なる場合、常に異なるものと判断します。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-strict-equality.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">x === y</pre> + +<h2 id="Description" name="Description">解説</h2> + +<p>厳密等価演算子 (<code>===</code> および <code>!==</code>) は、<a class="external external-icon" href="http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.6" rel="noopener">厳密等価比較アルゴリズム</a>を使用して二つのオペランドを比較します。</p> + +<ul> + <li>オペランドの型が異なる場合は、 <code>false</code> を返します。</li> + <li>両方のオペランドがオブジェクトである場合、同じオブジェクトを指している場合に限り <code>true</code> を返します。</li> + <li>両方のオペランドが <code>null</code> または両方のオペランドが <code>undefined</code> であった場合は <code>true</code> を返します。</li> + <li>どちらかのオペランドが <code>NaN</code> であった場合は <code>false</code> を返します。</li> + <li>それ以外の場合は、二つのオペランドの値を比較します。 + <ul> + <li>数値型は同じ値の数値である必要があります。 <code>+0</code> と <code>-0</code> は同じ値と見なされます。</li> + <li>文字列型は同じ文字が同じ順序で並んでいる必要があります。</li> + <li>論理型は両方が <code>true</code> であるか両方が <code>false</code> である必要があります。</li> + </ul> + </li> +</ul> + +<p>この演算子と<a href="/ja/docs/Web/JavaScript/Reference/Operators/Equality">等価</a> (<code>==</code>) 演算子の最も顕著な違いは、オペランドの型が異なる場合、 <code>==</code> 演算子は比較前に同じ型に変換しようとすることです。</p> + +<h2 id="Examples" name="Examples">例</h2> + +<h3 id="Comparing_operands_of_the_same_type" name="Comparing_operands_of_the_same_type">オペランドが同じ型である場合の比較</h3> + +<pre class="brush: js notranslate">console.log("hello" === "hello"); // true +console.log("hello" === "hola"); // false + +console.log(3 === 3); // true +console.log(3 === 4); // false + +console.log(true === true); // true +console.log(true === false); // false + +console.log(null === null); // true</pre> + +<h3 id="Comparing_operands_of_different_types" name="Comparing_operands_of_different_types">オペランドが異なる方である場合の比較</h3> + +<pre class="brush: js notranslate">console.log("3" === 3); // false + +console.log(true === 1); // false + +console.log(null === undefined); // false</pre> + +<h3 id="オブジェクトの比較">オブジェクトの比較</h3> + +<pre class="brush: js notranslate">const object1 = { + name: "hello" +} + +const object2 = { + name: "hello" +} + +console.log(object1 === object2); // false +console.log(object1 === object1); // true</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-equality-operators', 'Equality operators')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">ブラウザーの互換性</h2> + +<div class="hidden">このページの互換性一覧表は構造化データから生成されています。データに協力していただけるのであれば、 <a class="external" href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> をチェックアウトしてプルリクエストを送信してください。</div> + +<p>{{Compat("javascript.operators.strict_inequality")}}</p> + +<h2 id="See_also" name="See_also">関連情報</h2> + +<ul> + <li><a href="/ja/docs/Web/JavaScript/Reference/Operators/Equality">等価演算子</a></li> + <li><a href="/ja/docs/Web/JavaScript/Reference/Operators/Inequality">不等価演算子</a></li> + <li><a href="/ja/docs/Web/JavaScript/Reference/Operators/Strict_equality">厳密等価演算子</a></li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/strict_inequality/index.html b/files/ja/web/javascript/reference/operators/strict_inequality/index.html new file mode 100644 index 0000000000..189e872104 --- /dev/null +++ b/files/ja/web/javascript/reference/operators/strict_inequality/index.html @@ -0,0 +1,102 @@ +--- +title: 厳密不等価 (!==) +slug: Web/JavaScript/Reference/Operators/Strict_inequality +tags: + - JavaScript + - Language feature + - Operator + - Reference + - 演算子 + - 言語機能 +translation_of: Web/JavaScript/Reference/Operators/Strict_inequality +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>厳密不等価演算子 (<code>!==</code>) は、二つのオペランドが等しくないことを検査し、論理値で結果を返します <a href="/ja/docs/Web/JavaScript/Reference/Operators/Inequality">不等価</a>演算子とは異なり、厳密不等価演算子はオペランドの型が異なる場合、常に異なると判断します。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-strict-equality.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">x !== y</pre> + +<h2 id="Description" name="Description">解説</h2> + +<p>厳密不等価演算子は、オペランドが等しくないことを検査します。これは<a href="/ja/docs/Web/JavaScript/Reference/Operators/Strict_equality">厳密等価</a>演算子の逆に当たるので、以下の2行は常に同じ結果を生み出します。</p> + +<pre class="brush: js notranslate">x !== y + +!(x === y)</pre> + +<p>比較アルゴリズムの詳細については、<a href="/ja/docs/Web/JavaScript/Reference/Operators/Strict_equality">厳密等価</a>演算子のページをご覧ください。</p> + +<p>厳密等価演算子とと同様に、厳密不等価演算子はオペランドの型が異なると、常に異なるものと見なします。</p> + +<pre class="brush: js notranslate">3 !== "3"; // true</pre> + +<h2 id="Examples" name="Examples">例</h2> + +<h3 id="Comparing_operands_of_the_same_type" name="Comparing_operands_of_the_same_type">オペランドが同じ型である場合の比較</h3> + +<pre class="brush: js notranslate">console.log("hello" !== "hello"); // false +console.log("hello" !== "hola"); // true + +console.log(3 !== 3); // false +console.log(3 !== 4); // true + +console.log(true !== true); // false +console.log(true !== false); // true + +console.log(null !== null); // false</pre> + +<h3 id="Comparing_operands_of_different_types" name="Comparing_operands_of_different_types">オペランドが異なる方である場合の比較</h3> + +<pre class="brush: js notranslate">console.log("3" !== 3); // true + +console.log(true !== 1); // true + +console.log(null !== undefined); // true</pre> + +<h3 id="オブジェクトの比較">オブジェクトの比較</h3> + +<pre class="brush: js notranslate">const object1 = { + name: "hello" +} + +const object2 = { + name: "hello" +} + +console.log(object1 !== object2); // true +console.log(object1 !== object1); // false</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-equality-operators', 'Equality operators')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">ブラウザーの互換性</h2> + +<div class="hidden">このページの互換性一覧表は構造化データから生成されています。データに協力していただけるのであれば、 <a class="external" href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> をチェックアウトしてプルリクエストを送信してください。</div> + +<p>{{Compat("javascript.operators.strict_inequality")}}</p> + +<h2 id="See_also" name="See_also">関連情報</h2> + +<ul> + <li><a href="/ja/docs/Web/JavaScript/Reference/Operators/Equality">等価演算子</a></li> + <li><a href="/ja/docs/Web/JavaScript/Reference/Operators/Inequality">不等価演算子</a></li> + <li><a href="/ja/docs/Web/JavaScript/Reference/Operators/Strict_equality">厳密等価演算子</a></li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/subtraction/index.html b/files/ja/web/javascript/reference/operators/subtraction/index.html new file mode 100644 index 0000000000..499b95bd50 --- /dev/null +++ b/files/ja/web/javascript/reference/operators/subtraction/index.html @@ -0,0 +1,68 @@ +--- +title: 減算 (-) +slug: Web/JavaScript/Reference/Operators/Subtraction +tags: + - JavaScript + - Language feature + - Operator + - Reference +translation_of: Web/JavaScript/Reference/Operators/Subtraction +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>減算演算子 (<code>-</code>) は2つのオペランドを減算し、それらの差を生成します。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-subtraction.html")}}</div> + +<div></div> + + + +<h2 id="構文">構文</h2> + +<pre class="syntaxbox notranslate"><strong>Operator:</strong> <var>x</var> - <var>y</var> +</pre> + +<h2 id="例">例</h2> + +<h3 id="数値による減算">数値による減算</h3> + +<pre class="brush: js notranslate">5 - 3 // 2 +3 - 5 // -2</pre> + +<h3 id="非数による減算">非数による減算</h3> + +<pre class="brush: js notranslate">'foo' - 3 // NaN</pre> + +<h2 id="仕様">仕様</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">仕様</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-subtraction-operator-minus', 'Subtraction operator')}}</td> + </tr> + </tbody> +</table> + +<h2 id="ブラウザーの互換性">ブラウザーの互換性</h2> + + + +<p>{{Compat("javascript.operators.subtraction")}}</p> + +<h2 id="関連項目">関連項目</h2> + +<ul> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Addition">加算演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Multiplication">乗算演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Division">除算演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Remainder">剰余演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Exponentiation">べき乗演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Increment">インクリメント演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Decrement">デクリメント演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Unary_negation">単項マイナス演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Unary_plus">単項プラス演算子</a></li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/subtraction_assignment/index.html b/files/ja/web/javascript/reference/operators/subtraction_assignment/index.html new file mode 100644 index 0000000000..67fecfed23 --- /dev/null +++ b/files/ja/web/javascript/reference/operators/subtraction_assignment/index.html @@ -0,0 +1,61 @@ +--- +title: 減算代入 (-=) +slug: Web/JavaScript/Reference/Operators/Subtraction_assignment +tags: + - Assignment operator + - JavaScript + - Language feature + - Operator + - Reference +translation_of: Web/JavaScript/Reference/Operators/Subtraction_assignment +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>減算代入演算子 (<code>-=</code>) は、変数から右辺のオペランドの値を減算し、結果を変数に代入します。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-subtraction-assignment.html")}}</div> + +<div></div> + + + +<h2 id="構文">構文</h2> + +<pre class="syntaxbox notranslate"><strong>Operator:</strong> x -= y +<strong>Meaning:</strong> x = x - y</pre> + +<h2 id="例">例</h2> + +<h3 id="減算代入の使用">減算代入の使用</h3> + +<pre class="brush: js notranslate">// 次の変数を想定 +// bar = 5 + +bar -= 2 // 3 +bar -= 'foo' // NaN</pre> + +<h2 id="仕様">仕様</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">仕様</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-assignment-operators', 'Assignment operators')}}</td> + </tr> + </tbody> +</table> + +<h2 id="ブラウザーの互換性">ブラウザーの互換性</h2> + + + +<p>{{Compat("javascript.operators.subtraction_assignment")}}</p> + +<h2 id="関連項目">関連項目</h2> + +<ul> + <li><a href="/docs/Web/JavaScript/Guide/Expressions_and_Operators#Assignment">代入演算子</a></li> + <li><a href="/docs/Web/JavaScript/Reference/Operators/Subtraction">減算演算子</a></li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/super/index.html b/files/ja/web/javascript/reference/operators/super/index.html new file mode 100644 index 0000000000..f4787e8d5f --- /dev/null +++ b/files/ja/web/javascript/reference/operators/super/index.html @@ -0,0 +1,176 @@ +--- +title: super +slug: Web/JavaScript/Reference/Operators/super +tags: + - Classes + - ECMAScript 2015 + - JavaScript + - Language feature + - Left-hand-side expressions + - Operator +translation_of: Web/JavaScript/Reference/Operators/super +--- +<div>{{jsSidebar("Operators")}}</div> + +<p><strong>super</strong> キーワードは、オブジェクトの親の関数を呼び出すために使用できます。</p> + +<p><code>super.prop</code> および <code>super[expr]</code> 式は、<a href="/ja/docs/Web/JavaScript/Reference/Classes">class</a> と <a href="/ja/docs/Web/JavaScript/Reference/Operators/Object_initializer">オブジェクトリテラル</a> の両方におけるあらゆる<a href="/ja/docs/Web/JavaScript/Reference/Functions/Method_definitions">メソッド定義</a>で有効です。</p> + +<h2 id="Syntax" name="Syntax">構文</h2> + +<pre class="syntaxbox notranslate">super([arguments]); // 親コンストラクターを呼び出します。 +super.functionOnParent([arguments]); +</pre> + +<h2 id="Description" name="Description">解説</h2> + +<p>コンストラクターで使用する場合、<code>super</code> キーワードを単独で置き、<code>this</code> キーワードが使われる前に使用する必要があります。<code>super</code> キーワードは、親オブジェクトの関数を呼び出すためにも使用できます。</p> + +<h2 id="Example" name="Example">例</h2> + +<h3 id="Using_super_in_classes" name="Using_super_in_classes">クラス内での <code>super</code> の使用</h3> + +<p>このコードスニペットは、<a href="https://github.com/GoogleChrome/samples/blob/gh-pages/classes-es6/index.html">classes sample</a> (<a href="https://googlechrome.github.io/samples/classes-es6/index.html">実際のデモ</a>) からとっています。<code>super()</code> を利用することで、<code>Rectangle</code> と <code>Square</code> のコンストラクターに共通する処理を重複して記述しないようにしています。</p> + +<pre class="brush: js notranslate">class Rectangle { + constructor(height, width) { + this.name = 'Rectangle'; + this.height = height; + this.width = width; + } + sayName() { + console.log('Hi, I am a ', this.name + '.'); + } + get area() { + return this.height * this.width; + } + set area(value) { + this.height = this.width = Math.sqrt(value); + } +} + +class Square extends Rectangle { + constructor(length) { + this.height; // ReferenceError になります。super を先に呼び出さなければなりません! + + // length の値で親クラスの constructor を呼びます。 + // Rectangle の width と height になります。 + super(length, length); + + // Note: 'this' を使う前に super() をコールしなければなりません。 + // でないと reference error になります。 + this.name = 'Square'; + } +}</pre> + +<h3 id="Super-calling_static_methods" name="Super-calling_static_methods">静的メソッドでの super の呼び出し</h3> + +<p><a href="/ja/docs/Web/JavaScript/Reference/Classes/static">static</a> メソッドでも super を呼び出すことができます。</p> + +<pre class="brush: js notranslate">class Rectangle { + constructor() {} + static logNbSides() { + return 'I have 4 sides'; + } +} + +class Square extends Rectangle { + constructor() {} + static logDescription() { + return super.logNbSides() + ' which are all equal'; + } +} +Square.logDescription(); // 'I have 4 sides which are all equal' +</pre> + +<h3 id="Deleting_super_properties_will_throw_an_error" name="Deleting_super_properties_will_throw_an_error">super プロパティの削除でエラーが発生</h3> + +<p>親クラスのプロパティを削除するために、<a href="/ja/docs/Web/JavaScript/Reference/Operators/delete">delete 演算子</a> や <code>super.prop</code>、<code>super[expr]</code> を使うことはできません。{{jsxref("ReferenceError")}} がスローされます。</p> + +<pre class="brush: js notranslate">class Base { + constructor() {} + foo() {} +} +class Derived extends Base { + constructor() {} + delete() { + delete super.foo; // this is bad + } +} + +new Derived().delete(); // ReferenceError: invalid delete involving 'super'. </pre> + +<h3 id="super.prop_cannot_overwrite_non-writable_properties" name="super.prop_cannot_overwrite_non-writable_properties"><code>super.prop</code> は書き込み不可能なプロパティを上書きできない</h3> + +<p>{{jsxref("Object.defineProperty")}} などで書き込み不可プロパティを定義した場合、<code>super</code> はプロパティの値を上書きできません。</p> + +<pre class="brush: js notranslate">class X { + constructor() { + Object.defineProperty(this, 'prop', { + configurable: true, + writable: false, + value: 1 + }); + } +} + +class Y extends X { + constructor() { + super(); + } + foo() { + super.prop = 2; // 値を上書きできない + } +} + +var y = new Y(); +y.foo(); // TypeError: "prop" は読み取り専用 +console.log(y.prop); // 1 +</pre> + +<h3 id="Using_super.prop_in_object_literals" name="Using_super.prop_in_object_literals">オブジェクトリテラル内での <code>super.prop</code> の使用</h3> + +<p>super は <a href="/ja/docs/Web/JavaScript/Reference/Operators/Object_initializer">object initializer / literal</a> 記法内でも使用できます。この例では、二つのオブジェクトがメソッドを定義しています。二つ目のオブジェクトの中で、<code>super</code> が最初のオブジェクトのメソッドを呼び出しています。これは {{jsxref("Object.setPrototypeOf()")}} の助けで動作し、これは <code>obj2</code> のプロトタイプを <code>obj1</code> に設定するので、<code>super</code> は <code>method1</code> を <code>obj1</code> 上で見つけることができます。</p> + +<pre class="brush: js notranslate">var obj1 = { + method1() { + console.log('method 1'); + } +} + +var obj2 = { + method2() { + super.method1(); + } +} + +Object.setPrototypeOf(obj2, obj1); +obj2.method2(); // logs "method 1" +</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-super-keyword', 'super')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">ブラウザー実装状況</h2> + + + +<p>{{Compat("javascript.operators.super")}}</p> + +<h2 id="See_also" name="See_also">関連情報</h2> + +<ul> + <li><a href="/ja/docs/Web/JavaScript/Reference/Classes">クラス</a></li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/this/index.html b/files/ja/web/javascript/reference/operators/this/index.html new file mode 100644 index 0000000000..25f4f68a40 --- /dev/null +++ b/files/ja/web/javascript/reference/operators/this/index.html @@ -0,0 +1,488 @@ +--- +title: this +slug: Web/JavaScript/Reference/Operators/this +tags: + - JavaScript + - Language feature + - Operator + - Primary Expressions + - Reference + - this + - 演算子 + - 言語機能 +translation_of: Web/JavaScript/Reference/Operators/this +--- +<div>{{jsSidebar("Operators")}}</div> + +<p><strong>関数の <code>this</code> キーワード</strong> は、JavaScript ではほかの言語と少々異なる動作をします。また、<a href="/ja/docs/Web/JavaScript/Reference/Strict_mode">厳格モード</a>と非厳格モードでも違いがあります。</p> + +<p>ほとんどの場合、<code>this</code> の値はどのように関数が呼ばれたかによって決定されます(実行時結合)。これは実行時に割り当てできず、関数が呼び出されるたびに異なる可能性があります。ES5 では、関数が{{jsxref('Operators/this', "どのように呼ばれたかに関係なく <code>this</code> の値を設定する", 'The_bind_method', 1)}} {{jsxref("Function.prototype.bind()", "bind()")}} メソッドが導入され、ES2015 では、独自の <code>this</code> バインディングを行わない<a href="/ja/docs/Web/JavaScript/Reference/Functions/Arrow_functions">アロー関数</a>が導入されました(これは包含するレキシカルコンテキストの <code>this</code> の値を保持します)。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-this.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">this</pre> + +<h3 id="Value" name="Value">値</h3> + +<p>非厳格モードでは、実行コンテキスト (グローバル、関数、eval) のプロパティで、常にオブジェクトへの参照です。厳格モードではどのような値でも取り得ます。</p> + +<h2 id="解説">解説</h2> + +<h3 id="Global_context" name="Global_context">グローバルコンテキスト</h3> + +<p>グローバル実行コンテキスト (すべての関数の外側) では、厳格モードであるかどうかにかかわらず、<code>this</code> はグローバルオブジェクトを参照します。</p> + +<pre class="brush:js notranslate">// ウェブブラウザーでは window オブジェクトもグローバルオブジェクトです。 +console.log(this === window); // true + +a = 37; +console.log(window.a); // 37 + +this.b = "MDN"; +console.log(window.b) // "MDN" +console.log(b) // "MDN" +</pre> + +<div class="blockIndicator note"> +<p><strong>メモ:</strong> コードが実行されている現在のコンテキストに関係なく、グローバルの {{jsxref("globalThis")}} プロパティを使用していつでも簡単にグローバルオブジェクトを取得できます。</p> +</div> + +<h3 id="Function_context" name="Function_context">関数コンテキスト</h3> + +<p>関数内での <code>this</code> の値は、関数の呼び出され方によって異なります。</p> + +<p>下記のコードは<a href="/ja/docs/Web/JavaScript/Reference/Strict_mode">厳格モード</a>ではないため、また呼び出し時に <code>this</code> の値が設定されないため、<code>this</code> は既定でグローバルオブジェクトとなり、これはブラウザーでは {{domxref("Window", "window")}} です。</p> + +<pre class="brush:js notranslate">function f1() { + return this; +} + +// ブラウザー上で +f1() === window; // true + +// Node 上で +f1() === global; // true</pre> + +<p>ただし厳格モードでは、実行コンテキストに入るときに <code>this</code> 値が設定されていないと、以下の例のように <code>undefined</code> のままになります。</p> + +<pre class="brush:js notranslate">function f2() { + 'use strict'; // 厳格モードにする + return this; +} + +f2() === undefined; // true +</pre> + +<div class="note">二番目の例において、<code>this</code> が {{jsxref("undefined")}} となるのは <code>f2</code> が直接呼び出されており、オブジェクトのメソッドやプロパティ (例えば <code>window.f2()</code>) ではないためです。この機能は初めて<a href="/ja/docs/Web/JavaScript/Reference/Strict_mode">厳格モード</a>への対応が始まったとき、一部のブラウザーが実装していませんでした。その結果、これらのブラウザーは不正確に <code>window</code> オブジェクトを返していました。</div> + +<p>関数の呼び出し時に <code>this</code> の値を特定の値に設定するには、以下の例のように {{jsxref("Function.prototype.call()", "call()")}} または {{jsxref("Function.prototype.apply()", "apply()")}} を使用します。</p> + +<h3 id="クラスコンテキスト">クラスコンテキスト</h3> + +<p><a href="/ja/docs/Web/JavaScript/Reference/Classes">クラス</a>は関数の機能であるため、クラスと関数の <code>this</code> の動作は似ています。ただし、いくつかの違いと注意点があります。</p> + +<p>クラスのコンストラクター内では、<code>this</code> は通常のオブジェクトです。クラス内のすべての非静的メソッドは <code>this</code> のプロトタイプに追加されます。</p> + +<pre class="brush: js notranslate">class Example { + constructor() { + const proto = Object.getPrototypeOf(this); + console.log(Object.getOwnPropertyNames(proto)); + } + first(){} + second(){} + static third(){} +} + +new Example(); // ['constructor', 'first', 'second'] +</pre> + +<div class="blockIndicator note"> +<p><strong>メモ:</strong> 静的メソッドは <code>this</code> のプロパティではありません。それらはクラス自体のプロパティです。</p> +</div> + +<h3 id="派生クラス">派生クラス</h3> + +<p>基本クラスのコンストラクターとは異なり、派生コンストラクターには初期の <code>this</code> バインディングがありません。{{jsxref("Operators/super", "super()")}} を呼び出すとコンストラクター内に <code>this</code> バインディングが作成され、基本的に以下のコードを評価する効果があります。ここで、Base は継承されたクラスです。</p> + +<pre class="brush: js notranslate">this = new Base();</pre> + +<div class="blockIndicator warning"> +<p><strong>警告:</strong> super() を呼び出す前に <code>this</code> を参照するとエラーが発生します。</p> +</div> + +<p>派生クラスは、<code>オブジェクト</code>を return するか、コンストラクターを持たない場合を除き、<code>super()</code> を呼び出す前に return することはできません。</p> + +<pre class="brush: js notranslate">class Base {} +class Good extends Base {} +class AlsoGood extends Base { + constructor() { + return {a: 5}; + } +} +class Bad extends Base { + constructor() {} +} + +new Good(); +new AlsoGood(); +new Bad(); // 参照エラー</pre> + +<h2 id="例">例</h2> + +<h3 id="関数コンテキスト内の_this">関数コンテキスト内の this</h3> + +<pre class="brush:js notranslate" dir="rtl">// オブジェクトを call や apply の最初の引数として渡すと、this がそれに結び付けられます +var obj = {a: 'Custom'}; + +// このプロパティはグローバルオブジェクトに設定されます +var a = 'Global'; + +function whatsThis() { + return this.a; // this の値は関数の呼び出し方によって変わります +function is called +} + +whatsThis(); // 関数内の this として 'Global' は設定されていないので、デフォルトではグローバル/ウィンドウオブジェクトになります。 +whatsThis.call(obj); // 関数内の this として 'Custom' が obj に設定されています +whatsThis.apply(obj); // 関数内の this として 'Custom' が obj に設定されています +</pre> + +<h3 id="this_とオブジェクト変換">this とオブジェクト変換</h3> + +<pre class="brush:js notranslate">function add(c, d) { + return this.a + this.b + c + d; +} + +var o = {a: 1, b: 3}; + +// 最初の引数は 'this' として使用する +// オブジェクトで、続く引数は関数呼び出しの +// 引数として使用されます。 +add.call(o, 5, 7); // 16 + +// 最初の引数は 'this' として使用する +// オブジェクトで、二番目の引数は関数呼び出しの +// 引数として使用される配列です。 +add.apply(o, [10, 20]); // 34 +</pre> + +<p>なお、非厳格モードにおいて、<code>call</code> と <code>apply</code> は、<code>this</code> として渡された値がオブジェクトではない場合、内部の <code>ToObject</code> 操作を利用してオブジェクトに変換しようします。<code>7</code> や <code>'foo'</code> のようなプリミティブが渡された場合、関連するコンストラクターを使用してオブジェクトに変換されます。たとえば、プリミティブの数値である <code>7</code> は <code>new Number(7)</code> であるかのようにオブジェクトに変換され、文字列の <code>'foo'</code> は <code>new String('foo')</code> であるかのようにオブジェクトに変換されます。</p> + +<pre class="brush:js notranslate">function bar() { + console.log(Object.prototype.toString.call(this)); +} + +bar.call(7); // [object Number] +bar.call('foo'); // [object String] +bar.call(undefined); // [object global] +</pre> + +<h3 id="The_bind_method" name="The_bind_method"><code>bind</code> メソッド</h3> + +<p>ECMAScript 5 で {{jsxref("Function.prototype.bind")}} が導入されました。<code>f.bind(someObject)</code> の呼び出しは、<code>f</code> と同じ内部とスコープを持つ新しい関数を生成し、ここが <code>this</code> が発生するオリジナルの関数ですが、関数がどのように使われるかにかかわらず、新しい関数では <code>bind</code> の最初の引数に永続的にバインドされます。</p> + +<pre class="brush:js notranslate">function f() { + return this.a; +} + +var g = f.bind({a: 'azerty'}); +console.log(g()); // azerty + +var h = g.bind({a: 'yoo'}); // bind は一度しか機能しない +console.log(h()); // azerty + +var o = {a: 37, f: f, g: g, h: h}; +console.log(o.a, o.f(), o.g(), o.h()); // 37,37, azerty, azerty +</pre> + +<h3 id="Arrow_functions" name="Arrow_functions">アロー関数</h3> + +<p><a href="/ja/docs/Web/JavaScript/Reference/Functions/Arrow_functions">アロー関数</a>では、<code>this</code> はそれを囲むレキシカルコンテキストの <code>this</code> の値が設定されます。グローバルコードでは、グローバルオブジェクトが設定されます。</p> + +<pre class="brush: js notranslate">var globalObject = this; +var foo = (() => this); +console.log(foo() === globalObject); // true</pre> + +<div class="note"> +<p>メモ: アロー関数の呼び出し時に <code>this</code> 引数が <code>call</code>, <code>bind</code>, <code>apply</code> に渡されても無視されます。呼び出しに引数を加えることはできますが、最初の引数 (<code>thisArg</code>) は <code>null</code> を設定してください</p> +</div> + +<pre class="brush: js notranslate">// オブジェクトのメソッドとして呼び出す。 +var obj = {func: foo}; +console.log(obj.func() === globalObject); // true + +// call を使用して this の設定を試みる +console.log(foo.call(obj) === globalObject); // true + +// bind を使用して this の設定を試みる +foo = foo.bind(obj); +console.log(foo() === globalObject); // true</pre> + +<p>何があっても、<code>foo</code> の <code>this</code> は生成されたときの値が設定されています (上記の例ではグローバルオブジェクトです)。同様のことが、ほかの関数内で生成したアロー関数にも適用されます。それらの <code>this</code> には、それを包含するレキシカルコンテキストのものになります。</p> + +<pre class="brush:js notranslate">// this を返す関数を返す bar メソッドを持つ +// obj を生成します。返された関数はアロー関数 +// として生成されているため、その this は +// それを包含する関数の this に永続的に拘束 +// されます。bar の値は呼び出し時に設定でき、 +// 返値の関数の値に順に設定します。 +var obj = { + bar: function() { + var x = (() => this); + return x; + } +}; + +// bar を obj のメソッドとして呼び出す際、その this を obj に設定します +// 返値の関数への参照を fn に割り当てます。 +var fn = obj.bar(); + +// 厳格モードでは、this を設定せずに fn を呼び出すと +// 通常はグローバルオブジェクトか undefined が既定値となります。 +console.log(fn() === obj); // true + +// しかし obj のメソッドを call することなく参照するのは要注意です。 +var fn2 = obj.bar; +// するとアロー関数の呼び出しで this は bar の +// this に従うため window と同じになります。 +console.log(fn2()() == window); // true +</pre> + +<p>上記では、関数 (この無名関数を A と呼びます) に <code>obj.bar</code> が返すアロー関数として生成されたほかの関数 (この無名関数を B と呼びます) を割り当てています。結果として、呼び出されたときに関数 B の <code>this</code> は、永続的に <code>obj.bar</code> (関数 A) の <code>this</code> が設定されます。返された関数 (関数 B) が呼びされるとき、その <code>this</code> は常に最初に設定されたものになります。上記のコード例では、関数 B の <code>this</code> は <code>obj</code> である関数 A の <code>this</code> が設定されているため、通常はその <code>this</code> に <code>undefined</code> かグローバルオブジェクト (または、以前の例のグローバルコンテキストのように、いずれかのメソッド) が設定されますが、<code>obj</code> の設定が残ります。</p> + +<h3 id="As_an_object_method" name="As_an_object_method">オブジェクトのメソッドとして</h3> + +<p>関数がオブジェクトのメソッドとして呼び出されるとき、その <code>this</code> にはメソッドが呼び出されたオブジェクトが設定されます。</p> + +<p>次の例では、<code>o.f()</code> が起動したとき、関数内の <code>this</code> には、<code>o</code> オブジェクトが関連付けられます。</p> + +<pre class="brush:js notranslate">var o = { + prop: 37, + f: function() { + return this.prop; + } +}; + +console.log(o.f()); // 37 +</pre> + +<p>この振る舞いは、関数定義の方法や場所に全く影響を受けないことに注意してください。前述の例では、<code>o</code> の定義中に <code>f</code> メンバーとして関数をインラインに定義しています。しかし、関数を最初に定義して、後から <code>o.f</code> に付け足すことができます。その結果は同じ振る舞いになります。</p> + +<pre class="brush:js notranslate">var o = {prop: 37}; + +function independent() { + return this.prop; +} + +o.f = independent; + +console.log(o.f()); // 37 +</pre> + +<p>これは、関数が <code>o</code> の <code>f</code> のメンバーとして呼び出されることだけが重要なことを示しています。</p> + +<p>同様に、<code>this</code> の関連付けは、最も直近のメンバー参照にのみ影響を受けます。次の例では、関数が呼び出すとき、オブジェクト <code>o.b</code> の <code>g</code> メソッドとして呼び出しています。実行時に、関数内の <code>this</code> は <code>o.b</code> を参照します。オブジェクト自体が <code>o</code> のメンバーであるという事実は何の意味もありません。最も直近の参照のみが重要なのです。</p> + +<pre class="brush:js notranslate">o.b = {g: independent, prop: 42}; +console.log(o.b.g()); // 42 +</pre> + +<h4 id="this_on_the_objects_prototype_chain" name="this_on_the_objects_prototype_chain">オブジェクトのプロトタイプチェーン上の <code>this</code></h4> + +<p>同じ概念が、オブジェクトのプロトタイプチェーンのどこかに定義されたメソッドにも当てはまります。メソッドがオブジェクトのプロトタイプチェーン上にあった場合、メソッドがオブジェクト上にあるかのように、<code>this</code> はメソッドを呼び出したオブジェクトを参照します。</p> + +<pre class="brush:js notranslate">var o = {f: function() { return this.a + this.b; }}; +var p = Object.create(o); +p.a = 1; +p.b = 4; + +console.log(p.f()); // 5 +</pre> + +<p>この例では、変数 <code>p</code> に割り当てられたオブジェクト自身は <code>f</code> プロパティを持たず、プロトタイプから継承しています。しかし、<code>f</code> に対する検索が、最終的に <code>o</code> でその名前を持つメンバーを見つけることは重要ではありません。検索は <code>p.f</code> への参照から開始されるため、関数内の <code>this</code> は <code>p</code> として参照されるオブジェクトの値を取ります。<code>f</code> は <code>p</code> のメソッドとして呼ばれたため、その <code>this</code> は <code>p</code> を参照します。これは、JavaScript のプロトタイプ継承の興味深い機能です。</p> + +<h4 id="this_with_a_getter_or_setter" name="this_with_a_getter_or_setter">ゲッター/セッターと <code>this</code></h4> + +<p>再度、同じ概念が、ゲッターやセッターから呼ばれる関数にも当てはまります。ゲッターやセッターとして使用される関数は、このプロパティを設定するか、または得られている元のオブジェクトに関連付けられている <code>this</code> を持ちます。</p> + +<pre class="brush:js notranslate">function sum() { + return this.a + this.b + this.c; +} + +var o = { + a: 1, + b: 2, + c: 3, + get average() { + return (this.a + this.b + this.c) / 3; + } +}; + +Object.defineProperty(o, 'sum', { + get: sum, enumerable: true, configurable: true}); + +console.log(o.average, o.sum); // 2, 6 +</pre> + +<h3 id="As_a_constructor" name="As_a_constructor">コンストラクターとして</h3> + +<p>関数がコンストラクターとして ({{jsxref("Operators/new", "new")}} キーワードとともに) 使用されたとき、その <code>this</code> は生成された新しいオブジェクトに関連付けられます。</p> + +<div class="note"> +<p>コンストラクターの既定では、<code>this</code> で参照されるオブジェクトを返しますが、代わりにほかのオブジェクトを返すことができます (返値がオブジェクトではない場合、<code>this</code> オブジェクトが返されます)。</p> +</div> + +<pre class="brush:js notranslate">/* + * Constructors work like this: + * + * function MyConstructor(){ + * // Actual function body code goes here. + * // Create properties on |this| as + * // desired by assigning to them. E.g., + * this.fum = "nom"; + * // et cetera... + * + * // If the function has a return statement that + * // returns an object, that object will be the + * // result of the |new| expression. Otherwise, + * // the result of the expression is the object + * // currently bound to |this| + * // (i.e., the common case most usually seen). + * } + */ + +function C() { + this.a = 37; +} + +var o = new C(); +console.log(o.a); // 37 + + +function C2() { + this.a = 37; + return {a: 38}; +} + +o = new C2(); +console.log(o.a); // 38 +</pre> + +<p>最後の例 (<code>C2</code>) では、構築中にオブジェクトを返しているので、<code>this</code> が結び付けられている新しいオブジェクトは単に破棄されています。(これは根本的に "<code>this.a = 37;</code>" ステートメントを死んだコードにしてしまっています。これは実行されるので、正確には死んだコードではありませんが、外部への影響がありません。)</p> + +<h3 id="As_a_DOM_event_handler" name="As_a_DOM_event_handler">DOM イベントハンドラーとして</h3> + +<p>関数がイベントハンドラとして使用された場合、その <code>this</code> はリスナーが配置されている要素に設定されます ({{domxref("EventTarget/addEventListener", "addEventListener()")}} 以外のメソッドで動的に追加されたリスナーについては、この規約に従わないブラウザー-もあります)。</p> + +<pre class="brush:js notranslate">// リスナーとして呼び出された場合は、関連づけられた要素を青にする +function bluify(e) { + // 常に true + console.log(this === e.currentTarget); + // currentTarget と target が同じオブジェクトであれば true + console.log(this === e.target); + this.style.backgroundColor = '#A5D9F3'; +} + +// 文書内の各要素の一覧を取得 +var elements = document.getElementsByTagName('*'); + +// クリックリスナーとして bluify を追加することで、 +// 要素をクリックすると青くなるようになる +for(var i = 0 ; i < elements.length; i++){ + elements[i].addEventListener('click', bluify, false); +}</pre> + +<h3 id="In_an_inline_event_handler" name="In_an_inline_event_handler">インラインイベントハンドラー内</h3> + +<p>コードがインラインの <a href="/ja/docs/Web/Guide/Events/Event_handlers">on-イベントハンドラー</a>から呼び出されたとき、その <code>this</code> にはリスナーが配置されている DOM 要素が設定されます。</p> + +<pre class="brush:js notranslate"><button onclick="alert(this.tagName.toLowerCase());"> + Show this +</button> +</pre> + +<p>上記のアラートは <code>button</code> と表示します。ただし、外側のコードがこのように設定された <code>this</code> を持っているだけだということに注意してください。</p> + +<pre class="brush:js notranslate"><button onclick="alert((function() { return this; })());"> + Show inner this +</button> +</pre> + +<p>この場合、内側の関数の <code>this</code> は設定されていないので、グローバルの window オブジェクトを返します (つまり、<code>this</code> が呼び出しによって設定されていないので、非厳格モードの既定オブジェクトです)。</p> + +<h3 id="クラスの中の_this">クラスの中の this</h3> + +<div class="blockIndicator note"></div> + +<p>通常の関数と同様に、メソッド内の <code>this</code> の値は、どのように呼び出されるかによって異なります。クラス内の <code>this</code> が常にクラスのインスタンスを参照するように、この動作をオーバーライドしておくと便利な場合もあります。これを実現するには、コンストラクターでクラスのメソッドをバインドします。</p> + +<pre class="brush: js notranslate">class Car { + constructor() { + // 違いを示すために sayHi ではなく sayBye をバインドする + this.sayBye = this.sayBye.bind(this); + } + sayHi() { + console.log(`Hello from ${this.name}`); + } + sayBye() { + console.log(`Bye from ${this.name}`); + } + get name() { + return 'Ferrari'; + } +} + +class Bird { + get name() { + return 'Tweety'; + } +} + +const car = new Car(); +const bird = new Bird(); + +// メソッドの 'this' の値は呼び出し元に依存します +car.sayHi(); // Hello from Ferrari +bird.sayHi = car.sayHi; +bird.sayHi(); // Hello from Tweety + +// バインドされたメソッドの場合、'this' は呼び出し元に依存しません +bird.sayBye = car.sayBye; +bird.sayBye(); // Bye from Ferrari</pre> + +<div class="blockIndicator note"> +<p><strong>メモ:</strong> クラスは常に厳格モードのコードです。これを定義せずに <code>this</code> でメソッドを呼び出すとエラーが発生します。</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-this-keyword', 'The this keyword')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">ブラウザーの互換性</h2> + +<div class="hidden">このページの互換性一覧表は構造化データから生成されています。データに協力していただけるのであれば、<a class="external" href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> をチェックアウトしてプルリクエストを送信してください。</div> + +<p>{{Compat("javascript.operators.this")}}</p> + +<h2 id="See_also" name="See_also">関連情報</h2> + +<ul> + <li><a href="/ja/docs/Web/JavaScript/Reference/Strict_mode">厳格モード</a></li> + <li><a href="https://dmitripavlutin.com/gentle-explanation-of-this-in-javascript/">Gentle explanation of 'this' keyword in JavaScript</a></li> + <li>Getting the global context: {{jsxref("globalThis")}}</li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/typeof/index.html b/files/ja/web/javascript/reference/operators/typeof/index.html new file mode 100644 index 0000000000..8f190dd7d3 --- /dev/null +++ b/files/ja/web/javascript/reference/operators/typeof/index.html @@ -0,0 +1,288 @@ +--- +title: typeof +slug: Web/JavaScript/Reference/Operators/typeof +tags: + - JavaScript + - Language feature + - Operator + - Reference + - Unary +translation_of: Web/JavaScript/Reference/Operators/typeof +--- +<div>{{jsSidebar("Operators")}}</div> + +<p><strong><code>typeof</code></strong> 演算子は、未評価のオペランドの型を示す文字列を返します。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-typeof.html")}}</div> + +<p class="hidden">このデモのソースファイルは GitHub リポジトリに格納されています。デモプロジェクトに協力したい場合は、<a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> をクローンしてプルリクエストを送信してください。</p> + +<h2 id="Syntax" name="Syntax">構文</h2> + +<p><code>typeof</code> 演算子の後に、オペランドを続けて書きます。</p> + +<pre class="syntaxbox notranslate">typeof <var>operand</var> +typeof(<var>operand</var>) +</pre> + +<h3 id="Parameters" name="Parameters">引数</h3> + +<p><code><var>operand</var></code> は、オブジェクトまたは<a href="/ja/docs/Glossary/Primitive">プリミティブ</a>型を表す式を返します。</p> + +<h2 id="Description" name="Description">解説</h2> + +<p>以下は <code>typeof</code> が返す事が出来る値 (文字列) の一覧表です。型とプリミティブの詳細については、<a href="/ja/docs/Web/JavaScript/Data_structures">JavaScript のデータ構造</a>のページも参照してください。</p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">型</th> + <th scope="col">返値</th> + </tr> + </thead> + <tbody> + <tr> + <td><a href="/ja/docs/Glossary/Undefined">Undefined</a></td> + <td><code>"undefined"</code></td> + </tr> + <tr> + <td><a href="/ja/docs/Glossary/Null">Null</a></td> + <td><code>"object"</code> (<a href="#typeof_null">下記参照</a>)</td> + </tr> + <tr> + <td><a href="/ja/docs/Glossary/Boolean">真偽値</a></td> + <td><code>"boolean"</code></td> + </tr> + <tr> + <td><a href="/ja/docs/Glossary/Number">数値</a></td> + <td><code>"number"</code></td> + </tr> + <tr> + <td><a href="/ja/docs/Glossary/BigInt">BigInt</a> (ECMAScript 2020 の新機能)</td> + <td><code>"bigint"</code></td> + </tr> + <tr> + <td><a href="/ja/docs/Glossary/String">文字列</a></td> + <td><code>"string"</code></td> + </tr> + <tr> + <td><a href="/ja/docs/Glossary/Symbol">シンボル</a> (ECMAScript 2015 の新機能)</td> + <td><code>"symbol"</code></td> + </tr> + <tr> + <td><a href="/ja/docs/Glossary/Function">Function</a> オブジェクト (implements [[Call]] in ECMA-262 terms)</td> + <td><code>"function"</code></td> + </tr> + <tr> + <td>その他のオブジェクト</td> + <td><code>"object"</code></td> + </tr> + </tbody> +</table> + +<div class="blockIndicator note"> +<p><strong>メモ:</strong> ECMAScript 2019 およびそれ以前の実装では、呼び出し可能な非標準のオブジェクトに対して、<code>typeof</code> が任意の実装定義の文字列値を返すことを許可していました。</p> + +<p>実際にこれを利用したブラウザーとして知られているのは、古い Internet Explorer だけです。(<a href="#IE-specific_notes">下記参照</a>)</p> +</div> + +<h2 id="Examples" name="Examples">例</h2> + +<h3 id="Basic_usage" name="Basic_usage">基本的な使い方</h3> + +<pre class="brush: js notranslate">// 数値 +typeof 37 === 'number'; +typeof 3.14 === 'number'; +typeof(42) === 'number'; +typeof Math.LN2 === 'number'; +typeof Infinity === 'number'; +typeof NaN === 'number'; // "Not-A-Number" であるにもかかわらず。 +typeof Number('1') === 'number'; // Number は数値に型強制できない値を含めて、 +typeof Number('shoe') === 'number'; // あらゆるものを数字に解析します。 + +typeof 42n === 'bigint'; + + +// 文字列 +typeof '' === 'string'; +typeof 'bla' === 'string'; +typeof `template literal` === 'string'; +typeof '1' === 'string'; // 文字列内の数値は文字列型のままです。 +typeof (typeof 1) === 'string'; // typeof は常に文字列を返します。 +typeof String(1) === 'string'; // String は何でも文字列に変換するので、toString よりも安全です。 + + +// 真偽値 +typeof true === 'boolean'; +typeof false === 'boolean'; +typeof Boolean(1) === 'boolean'; // Boolean は、値が truthy か falsy かに基づいて変換します。 + +typeof !!(1) === 'boolean'; // ! (論理 NOT) 演算子 2 つの呼び出しは、Boolean() と同等です。 + + +// シンボル +typeof Symbol() === 'symbol' +typeof Symbol('foo') === 'symbol' +typeof Symbol.iterator === 'symbol' + + +// Undefined +typeof undefined === 'undefined'; +typeof declaredButUndefinedVariable === 'undefined'; +typeof undeclaredVariable === 'undefined'; + + +// オブジェクト +typeof {a: 1} === 'object'; + +// <a href="/ja/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray">Array.isArray</a> または Object.prototype.toString.call を使用て、 +// 通常のオブジェクトと配列を区別します。 +typeof [1, 2, 4] === 'object'; + +typeof new Date() === 'object'; +typeof /regex/ === 'object'; // 過去の実装は<a href="#typeof_null">正規表現</a>を参照してください。 + + +// 以下のようなものは、紛らわしく、危険で、無駄なものです。それらの使用を避けてください。 +typeof new Boolean(true) === 'object'; +typeof new Number(1) === 'object'; +typeof new String('abc') === 'object'; + + +// 関数 +typeof function() {} === 'function'; +typeof class C {} === 'function'; +typeof Math.sin === 'function';</pre> + +<h3 id="typeof_null" name="typeof_null"><code>null 型</code></h3> + +<pre class="brush: js; no-line-numbers notranslate">// JavaScript の初期からの実装に基づく +typeof null === 'object'; +</pre> + +<p>JavaScript の最初の実装では、JavaScript の値は型タグと値で表現されていました。オブジェクトの型タグは <code>0</code> で、<code>null</code> は NULL ポインター (ほとんどのプラットフォームで <code>0x00</code>) として表されていました。その結果、<code>null</code> はタグの型として <code>0</code> を持っていたため、<code>typeof</code> の戻り値は <code>"object"</code> です。(<a href="http://www.2ality.com/2013/10/typeof-null.html">リファレンス</a>)</p> + +<p>ECMAScript の修正案が (オプトインを使用して) 提案されましたが、<a href="https://web.archive.org/web/20160331031419/http://wiki.ecmascript.org:80/doku.php?id=harmony:typeof_null">却下されました</a>。それは <code>typeof null === 'null'</code> という結果になるものでした。</p> + +<h3 id="Using_new_operator" name="Using_new_operator"><code>new</code> 演算子の使用</h3> + +<pre class="brush: js; notranslate">// Function コンストラクターを除くすべてのコンストラクター関数は、 +// 常に typeof 'object' です +let str = new String('String'); +let num = new Number(100); + +typeof str; // 'object' を返す +typeof num; // 'object' を返す + +let func = new Function(); + +typeof func; // 'function' を返す +</pre> + +<h3 id="Need_for_parentheses_in_Syntax" name="Need_for_parentheses_in_Syntax">構文で括弧が必要な場合</h3> + +<pre class="brush:js notranslate">// 式のデータ型を特定するために、かっこを使用することができます。 +let iData = 99; + +typeof iData + ' Wisen'; // 'number Wisen' +typeof (iData + ' Wisen'); // 'string' +</pre> + +<h3 id="Regular_expressions" name="Regular_expressions">正規表現</h3> + +<p>呼び出し可能な正規表現は、一部のブラウザーでは非標準的な追加機能でした。</p> + +<pre class="brush:js; no-line-numbers notranslate">typeof /s/ === 'function'; // Chrome 1-12 ECMAScript5.1 に非準拠 +typeof /s/ === 'object'; // Firefox 5+ ECMAScript 5.1 に準拠 +</pre> + +<h3 id="Errors" name="Errors">エラー</h3> + +<p>ECMAScript 2015 より前では、<code>typeof</code> は常にそれが供給されたオペランドの文字列を返すことが保証されていました。宣言されていない識別子があっても、<code>typeof</code> は <code>'undefined'</code> を返します。<code>typeof</code> を使用すると、エラーは発生しません。</p> + +<p>しかしながら、ブロックスコープの <code><a href="/ja/docs/Web/JavaScript/Reference/Statements/let">let</a></code> と <code><a href="/ja/docs/Web/JavaScript/Reference/Statements/const">const</a></code> が追加されたことで、変数が宣言される前のブロック内で <code>let</code> と <code>const</code> に <code>typeof</code> を使用すると(またはクラスに <code>typeof</code> を使用すると)、<code><a href="/ja/docs/Web/JavaScript/Reference/Global_Objects/ReferenceError">ReferenceError</a></code> が投げられます。ブロックスコープ内の変数は、ブロックの開始から初期化が処理されるまで「<a href="/ja/docs/Web/JavaScript/Reference/Statements/let#The_temporal_dead_zone_and_typeof">一時的なデッドゾーン</a>」にあり、その間にアクセスされるとエラーを投げます。</p> + +<pre class="brush: js; no-line-numbers notranslate">typeof undeclaredVariable === 'undefined'; + +typeof newLetVariable; // ReferenceError +typeof newConstVariable; // ReferenceError +typeof newClass; // ReferenceError + +let newLetVariable; +const newConstVariable = 'hello'; +class newClass{};</pre> + +<h3 id="Exceptions" name="Exceptions">例外</h3> + +<p>現在のブラウザーではすべて、標準外のホストオブジェクト {{domxref("document.all")}} は <code>undefined</code> 型になります。</p> + +<pre class="brush: js; no-line-numbers notranslate">typeof document.all === 'undefined';</pre> + +<p>仕様では、非標準のオブジェクトののためのカスタム型タグを許可していますが、それらの型タグは定義済みのものとは異なるものであることを要求しています。<code>document.all</code> が <code>'undefined'</code> という型を持っている場合、ウェブ標準ではオリジナルの ECMA JavaScript 標準の "故意の違反" として分類されています。</p> + +<h3 id="Real-world_usage" name="Real-world_usage">実際の使い方</h3> + +<p><code>typeof</code> は非常に便利ですが、汎用性はそれほど高くありません。たとえば、<code>typeof([])</code> は <code>typeof(new Date())</code> や <code>typeof(/abc/)</code> などと同様に <code>'object'</code> です。</p> + +<p>型のチェックをより具体的にするために、プロダクションレベルのコードで使用するための <code>typeof</code> ラッパーは以下のようになります。(<code>obj</code> が存在する場合)</p> + +<pre class="brush: js notranslate"> function type(obj, fullClass) { + + // obj の toPrototypeString() を取得します。(すべての型を処理します) + // 初期の JS 環境では null の場合 '[object Object]' を返すので、直接確認するのがベストです。 + if (fullClass) { + return (obj === null) ? '[object Null]' : Object.prototype.toString.call(obj); + } + if (obj == null) { return (obj + '').toLowerCase(); } // 暗黙の toString() 変換 + + var deepType = Object.prototype.toString.call(obj).slice(8,-1).toLowerCase(); + if (deepType === 'generatorfunction') { return 'function' } + + // 過剰な特異性を防いでください。(例えば、[object HTMLDivElement] など) + // 機能的な正規表現 (Android <=2.3)、機能的な <object> 要素 (Chrome <=57, Firefox <=52) などを考慮します。 + // String.prototype.match は普遍的にサポートされています。 + + return deepType.match(/^(array|bigint|date|error|function|generator|regexp|symbol)$/) ? deepType : + (typeof obj === 'object' || typeof obj === 'function') ? 'object' : typeof obj; + }</pre> + +<p>存在しない変数をチェックすると、{{JSxRef("ReferenceError")}} が投げられるため、<code>typeof nonExistentVar === 'undefined'</code> を使用します。</p> + +<h2 id="Specifications" name="Specifications">仕様</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">仕様書</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-typeof-operator', 'The typeof Operator')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">ブラウザー実装状況</h2> + + + +<p>{{Compat("javascript.operators.typeof")}}</p> + +<h3 id="IE-specific_notes" name="IE-specific_notes">IE 特有のメモ</h3> + +<p>IE 6、7、8 では、以下のように多くのホストオブジェクトがオブジェクト型であり、関数ではありません。</p> + +<pre class="brush: js; no-line-numbers notranslate">typeof alert === 'object'</pre> + +<p>一部の非標準 IE プロパティは他の値を返します。(<a href="https://github.com/tc39/ecma262/issues/1440#issuecomment-461963872">tc39/ecma262#1440 (comment)</a>)</p> + +<pre class="brush: js; no-line-numbers notranslate">typeof window.external.AddSearchProvider === "unknown"; +typeof window.external.IsSearchProviderInstalled === "unknown";</pre> + +<h2 id="See_also" name="See_also">関連情報</h2> + +<ul> + <li>{{JSxRef("Operators/instanceof", "instanceof")}}</li> + <li><a href="https://github.com/tc39/ecma262/issues/668"><code>document.all</code> willful violation of the standard</a></li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/unary_negation/index.html b/files/ja/web/javascript/reference/operators/unary_negation/index.html new file mode 100644 index 0000000000..69d2ea40c3 --- /dev/null +++ b/files/ja/web/javascript/reference/operators/unary_negation/index.html @@ -0,0 +1,80 @@ +--- +title: 単項マイナス (-) +slug: Web/JavaScript/Reference/Operators/Unary_negation +tags: + - JavaScript + - Language feature + - Operator + - Reference + - 演算子 + - 言語機能 +translation_of: Web/JavaScript/Reference/Operators/Unary_negation +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>単項マイナス演算子 (<code>-</code>) はオペランドの前に置かれ、符号を反転します。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-unary-negation.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"><strong>演算子:</strong> -<var>x</var> +</pre> + +<h2 id="Examples" name="Examples">例</h2> + +<h3 id="Negating_numbers" name="Negating_numbers">数値の符号を反転</h3> + +<pre class="brush: js notranslate">const x = 3; +const y = -x; + +// y = -3 +// x = 3 +</pre> + +<h3 id="Negating_non-numbers" name="Negating_non-numbers">数値以外の符号を反転</h3> + +<p>単項マイナス演算子は、数値でないものを数値に変換することができます。</p> + +<pre class="brush: js notranslate">const x = "4"; +const y = -x; + +// y = -4 +</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-unary-minus-operator', 'Unary negation operator')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">ブラウザーの互換性</h2> + +<div class="hidden">このページの互換性一覧表は構造化データから生成されています。データに協力していただけるのであれば、 <a class="external" href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> をチェックアウトしてプルリクエストを送信してください。</div> + +<p>{{Compat("javascript.operators.unary_negation")}}</p> + +<h2 id="See_also" name="See_also">関連情報</h2> + +<ul> + <li><a href="/ja/docs/Web/JavaScript/Reference/Operators/Addition">加算演算子</a></li> + <li><a href="/ja/docs/Web/JavaScript/Reference/Operators/Subtraction">減算演算子</a></li> + <li><a href="/ja/docs/Web/JavaScript/Reference/Operators/Division">除算演算子</a></li> + <li><a href="/ja/docs/Web/JavaScript/Reference/Operators/Multiplication">乗算演算子</a></li> + <li><a href="/ja/docs/Web/JavaScript/Reference/Operators/Remainder">剰余演算子</a></li> + <li><a href="/ja/docs/Web/JavaScript/Reference/Operators/Exponentiation">べき乗演算子</a></li> + <li><a href="/ja/docs/Web/JavaScript/Reference/Operators/Increment">インクリメント演算子</a></li> + <li><a href="/ja/docs/Web/JavaScript/Reference/Operators/Decrement">デクリメント演算子</a></li> + <li><a href="/ja/docs/Web/JavaScript/Reference/Operators/Unary_plus">単項プラス演算子</a></li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/unary_plus/index.html b/files/ja/web/javascript/reference/operators/unary_plus/index.html new file mode 100644 index 0000000000..6cd8b30087 --- /dev/null +++ b/files/ja/web/javascript/reference/operators/unary_plus/index.html @@ -0,0 +1,80 @@ +--- +title: 単項プラス (+) +slug: Web/JavaScript/Reference/Operators/Unary_plus +tags: + - JavaScript + - Language feature + - Operator + - Reference +translation_of: Web/JavaScript/Reference/Operators/Unary_plus +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>単項プラス演算子 (<code>+</code>) は、オペランドの前に置かれ、そのオペランドを評価し、それが数値以外の場合は数値に変換します。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-unary-plus.html", "taller")}}</div> + + + +<h2 id="例">例</h2> + +<pre class="syntaxbox notranslate"><strong>Operator:</strong> +<var>x</var> +</pre> + +<h2 id="説明">説明</h2> + +<p>単項マイナス (<code>-</code>) も非数値を数値に変換できますが、単項プラスは数値に対して他の演算を行わないため、非数値を数値に変換する最も高速で好ましい方法です。これは、整数や浮動小数点の文字列表現や、非文字列値である <code>true</code>、<code>false</code>、<code>null</code> を変換することができます。10進数と16進数(接頭辞 0x)の両形式の整数と負の数(16進数の負の数はサポートされていません)がサポートされています。BigInt 値に対してこの演算子を使用すると TypeError がスローされます。特定の値を解析できない場合は、{{jsxref("NaN")}} と評価されます。</p> + +<h2 id="例_2">例</h2> + +<h3 id="数値での使い方">数値での使い方</h3> + +<pre class="brush: js notranslate">const x = 1; +const y = -1; + +console.log(+x); +// 1 +console.log(+y); +// -1</pre> + +<h3 id="数値以外での使い方">数値以外での使い方</h3> + +<pre class="brush: js notranslate">+true // 1 ++false // 0 ++null // 0 ++function(val){ return val } // NaN ++1n // BigInt 値は数値に変換できないためエラーになります +</pre> + +<h2 id="仕様">仕様</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">仕様書</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-unary-plus-operator', 'Unary plus operator')}}</td> + </tr> + </tbody> +</table> + +<h2 id="ブラウザの互換性">ブラウザの互換性</h2> + + + +<p>{{Compat("javascript.operators.unary_plus")}}</p> + +<h2 id="関連情報">関連情報</h2> + +<ul> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Addition">加算演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Subtraction">減算演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Division">除算演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Multiplication">乗算演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Remainder">剰余演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Exponentiation">べき乗演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Increment">インクリメント演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Decrement">デクリメント演算子</a></li> + <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Unary_negation">単項マイナス演算子</a></li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/unsigned_right_shift/index.html b/files/ja/web/javascript/reference/operators/unsigned_right_shift/index.html new file mode 100644 index 0000000000..bca04162e0 --- /dev/null +++ b/files/ja/web/javascript/reference/operators/unsigned_right_shift/index.html @@ -0,0 +1,79 @@ +--- +title: 符号なし右シフト (>>>) +slug: Web/JavaScript/Reference/Operators/Unsigned_right_shift +tags: + - Bitwise operator + - JavaScript + - Language feature + - Operator + - Reference + - 演算子 + - 言語機能 +translation_of: Web/JavaScript/Reference/Operators/Unsigned_right_shift +--- +<div>{{jsSidebar("Operators")}}</div> + +<p><strong>符号なし右シフト演算子 (<code>>>></code>)</strong> (ゼロ埋め右シフト) は、1つ目のオペランドを指定されたビット数だけ右にずらします。右にずらしてあふれたビットは廃棄されます。0のビットが左からずれて入ります。符号ビットは <code>0</code> になりますので、結果は負の数にはなりません。他のビット毎演算子とは異なり、ゼロ埋め右シフトは符号なし32ビット整数を返します。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-unsigned-right-shift.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"><code><var>a</var> >>> <var>b</var></code> +</pre> + +<h2 id="Description" name="Description">解説</h2> + +<p>この演算子は、1つ目のオペランドを指定されたビット数だけ右にずらします。右にずらしてあふれたビットは廃棄されます。0のビットが左からずれて入ります。符号ビットは <code>0</code> になりますので、結果は負の数にはなりません。他のビット毎演算子とは異なり、ゼロ埋め右シフトは符号なし32ビット整数を返します。</p> + +<p>負の数ではない場合、ゼロ埋め右シフトと符号保存右シフトは同じ結果をになります。例えば、 <code>9 >>> 2</code> は 2 となり、 <code>9 >> 2</code> と同じになります。</p> + +<pre class="brush: js notranslate">. 9 (10進数): 00000000000000000000000000001001 (2進数) + -------------------------------- +9 >>> 2 (10進数): 00000000000000000000000000000010 (2進数) = 2 (10進数) +</pre> + +<p>しかし、これは負の数の場合は当てはまりません。例えば、 <code>-9 >>> 2</code> は 1073741821 になり、 <code>-9 >> 2</code> (<code>-3</code> になる) とは異なります。</p> + +<pre class="brush: js notranslate">. -9 (10進数): 11111111111111111111111111110111 (2進数) + -------------------------------- +-9 >>> 2 (10進数): 00111111111111111111111111111101 (2進数) = 1073741821 (10進数) +</pre> + +<h2 id="Examples" name="Examples">例</h2> + +<h3 id="Using_unsigned_right_shift" name="Using_unsigned_right_shift">符号なし右シフトの使用</h3> + +<pre class="brush: js notranslate"> 9 >>> 2; // 2 +-9 >>> 2; // 1073741821 +</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-bitwise-shift-operators', 'Bitwise Shift Operators')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">ブラウザーの互換性</h2> + +<div class="hidden">このページの互換性一覧表は構造化データから生成されています。データに協力していただけるのであれば、 <a class="external" href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> をチェックアウトしてプルリクエストを送信してください。</div> + +<p>{{Compat("javascript.operators.unsigned_right_shift")}}</p> + +<h2 id="See_also" name="See_also">関連情報</h2> + +<ul> + <li><a href="/ja/docs/Web/JavaScript/Guide/Expressions_and_Operators#Bitwise">代入演算子</a></li> + <li><a href="/ja/docs/Web/JavaScript/Reference/Operators/Unsigned_right_shift_assignment">符号なし右シフト代入演算子</a></li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/unsigned_right_shift_assignment/index.html b/files/ja/web/javascript/reference/operators/unsigned_right_shift_assignment/index.html new file mode 100644 index 0000000000..eb756b8c49 --- /dev/null +++ b/files/ja/web/javascript/reference/operators/unsigned_right_shift_assignment/index.html @@ -0,0 +1,61 @@ +--- +title: 符号なし右シフト代入 (>>>=) +slug: Web/JavaScript/Reference/Operators/Unsigned_right_shift_assignment +tags: + - Assignment operator + - JavaScript + - Language feature + - Operator + - Reference +translation_of: Web/JavaScript/Reference/Operators/Unsigned_right_shift_assignment +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>符号なし右シフト代入演算子 (<em><code>>>>=</code></em>) は、指定された量のビットを右に移動し、結果を変数に割り当てます。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-unsigned-right-shift-assignment.html")}}</div> + +<div></div> + + + +<h2 id="構文">構文</h2> + +<pre class="syntaxbox notranslate"><strong>Operator:</strong> x >>>= y +<strong>Meaning:</strong> x = x >>> y</pre> + +<h2 id="例">例</h2> + +<h3 id="符号なし右シフト代入の使用">符号なし右シフト代入の使用</h3> + +<pre class="brush: js notranslate">let a = 5; // (00000000000000000000000000000101) +a >>>= 2; // 1 (00000000000000000000000000000001) + +let b = -5; // (-00000000000000000000000000000101) +b >>>= 2; // 1073741822 (00111111111111111111111111111110)</pre> + +<h2 id="仕様">仕様</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">仕様</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-assignment-operators', 'Assignment operators')}}</td> + </tr> + </tbody> +</table> + +<h2 id="ブラウザーの互換性">ブラウザーの互換性</h2> + + + +<p>{{Compat("javascript.operators.unsigned_right_shift_assignment")}}</p> + +<h2 id="関連項目">関連項目</h2> + +<ul> + <li><a href="/docs/Web/JavaScript/Guide/Expressions_and_Operators#Assignment">代入演算子</a></li> + <li><a href="/docs/Web/JavaScript/Reference/Operators/Unsigned_right_shift">符号なし右シフト演算子</a></li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/void/index.html b/files/ja/web/javascript/reference/operators/void/index.html new file mode 100644 index 0000000000..eab7076612 --- /dev/null +++ b/files/ja/web/javascript/reference/operators/void/index.html @@ -0,0 +1,150 @@ +--- +title: void 演算子 +slug: Web/JavaScript/Reference/Operators/void +tags: + - JavaScript + - Operator + - URIs + - Unary +translation_of: Web/JavaScript/Reference/Operators/void +--- +<div>{{jsSidebar("Operators")}}</div> + +<p><strong><code>void</code> 演算子</strong>は与えられた式 (<em>expression</em>) を評価し、{{jsxref("Global_Objects/undefined", "undefined")}} を返します。</p> + +<h2 id="Syntax" name="Syntax">構文</h2> + +<pre class="syntaxbox"><code>void <em>expression</em></code></pre> + +<h2 id="Uses" name="Uses">説明</h2> + +<p>この演算子は、<strong>「戻り値が <code>undefined</code> であってほしい場所に、それ以外の戻り値を持つ式を挿入したい場合」</strong>に有用です。</p> + +<p><code>void</code> 演算子は単にプリミティブ値 undefined を得る目的でしばしば使われ、一般的に "<code>void(0)</code>" と書かれます(これは "<code>void 0</code>" と等価です)。この目的であれば、代わりに値が {{jsxref("Global_Objects/undefined", "undefined")}} の変数、未定義のグローバル変数などを使用する事もできます。</p> + +<p><a href="/ja/docs/Glossary/IIFE">即時実行関数式</a>を使用するとき、 <code>void</code> は、<code>function</code> キーワードを宣言の代わりに式として扱うように強制するために使用できます。</p> + +<pre class="brush: js">void function iife() { + var bar = function () {}; + var baz = function () {}; + var foo = function () { + bar(); + baz(); + }; + var biz = function () {}; + + foo(); + biz(); +}(); +</pre> + +<h2 id="JavaScript_URIs" name="JavaScript_URIs">JavaScript URI</h2> + +<p><code>javascript:</code> から始まる URI をサポートしたブラウザに於いて、それは、URI 内のコードを評価し、戻り値が {{jsxref("Global_Objects/undefined", "undefined")}} でなければ、返された値にページコンテンツを置き換えます。<code>void</code> 演算子は、{{jsxref("Global_Objects/undefined", "undefined")}} を返すために使用できます。たとえば:</p> + +<pre class="brush: html"><a href="javascript:void(0);"> + Click here to do nothing +</a> + +<a href="javascript:void(document.body.style.backgroundColor='green');"> + Click here for green background +</a> +</pre> + +<p>但し、<code>javascript:</code> 疑似プロトコルはあくまで控えめなイベントハンドラなどの代替であり、積極的に使用するべきではないでしょう。<br> + しかしながらこれは、戻り値を必要としないブックマークレットの作成の際などに役立つ場合があります。</p> + +<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('ESDraft', '#sec-void-operator', 'The void Operator')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-void-operator', 'The void Operator')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-11.4.2', 'The void Operator')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES3', '#sec-11.4.2', 'The void Operator')}}</td> + <td>{{Spec2('ES3')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES1', '#sec-11.4.2', 'The void Operator')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>初期定義。JavaScript 1.1 で実装。</td> + </tr> + </tbody> +</table> + +<h2 id="ブラウザ実装状況">ブラウザ実装状況</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>機能</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>基本サポート</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>機能</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>基本サポート</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="関連項目">関連項目</h2> + +<ul> + <li><code><a href="/ja/docs/Web/JavaScript/Reference/Global_Objects/undefined">undefined</a></code></li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/yield/index.html b/files/ja/web/javascript/reference/operators/yield/index.html new file mode 100644 index 0000000000..2cadddab3b --- /dev/null +++ b/files/ja/web/javascript/reference/operators/yield/index.html @@ -0,0 +1,106 @@ +--- +title: yield +slug: Web/JavaScript/Reference/Operators/yield +tags: + - ECMAScript 2015 + - Generators + - Iterator + - JavaScript + - Language feature + - Operator + - ジェネレーター + - 反復処理 + - 演算子 + - 言語機能 +translation_of: Web/JavaScript/Reference/Operators/yield +--- +<div>{{jsSidebar("Operators")}}</div> + +<p><code>yield</code> キーワードは、ジェネレーター関数 ({{jsxref("Statements/function*", "function*")}} または<a href="/ja/docs/Web/JavaScript/Reference/Statements/Legacy_generator_function">古いジェネレーター関数</a>) のを一時停止したり再開したりするために使用します。</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-yield.html", "taller")}}</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">[<var>rv</var>] = <strong>yield</strong> [<var>expression</var>]</pre> + +<dl> + <dt><code><var>expression</var></code> {{optional_inline}}</dt> + <dd><a href="/ja/docs/Web/JavaScript/Reference/Iteration_protocols#iterator">iterator プロトコル</a>経由でジェネレーター関数が返す値を定義します。省略した場合、代わりに <code>undefined</code> が返されます。</dd> + <dt><code><var>rv</var></code> {{optional_inline}}</dt> + <dd> + <p>ジェネレーターの実行を再開する <code>next()</code> メソッドに渡したオプションの値を受け取ります。</p> + </dd> +</dl> + +<h2 id="Description" name="Description">解説</h2> + +<p><code>yield</code> キーワードは、ジェネレーター関数の実行を一時停止し、ジェネレーターの呼び出し元に <code>yield</code> キーワードに続く値を戻します。これは、 <code>return</code> キーワードのジェネレーター版と考えることができます。</p> + +<p><code>yield</code> はそれを含むジェネレーター関数の中で直接しか呼び出すことしかできません。呼び出し先の関数やコールバックから呼び出すことはできません。</p> + +<p><code>yield</code> キーワードはジェネレーターの <code>next()</code> メソッドを呼び出させ、 <code>value</code> と <code>done</code> の2つのプロパティを持つ <code>IteratorResult</code> オブジェクトを返します。 <code>value</code> プロパティは <code>yield</code> 式の評価結果であり、 <code>done</code> は <code>false</code>、すなわちジェネレーター関数が完全には完了していないことを示します。</p> + +<p><code>yield</code> 式によって実行が停止されると、ジェネレーターの <code>next()</code> メソッドが呼び出されるまで、ジェネレーターのコード実行は一時停止します。ジェネレーターの <code>next()</code> メソッドが呼ばれるたびに、ジェネレーターの実行が再開され、次のうちのいずれかに達するまで実行されます。</p> + +<ul> + <li>ジェネレーターを再び停止して、ジェネレーターの新しい値を返す <code>yield</code>。再度 <code>next()</code> が呼ばれると <code>yield</code> の直後から実行が再開されます。</li> + <li>ジェネレーターから例外を発生させるために使用される {{jsxref("Statements/throw", "throw")}}。完全にジェネレーターの実行を停止し、 (通常の例外が発生した場合のように) 呼び出し元で実行が再開されます。</li> + <li>ジェネレーター関数の末尾。この場合、ジェネレーターの実行は終了し、 <code>IteratorResult</code> オブジェクトの <code>value</code> に {{jsxref("undefined")}} が、 <code>done</code> に <code>true</code> が代入されて呼び出し元に返されます。</li> + <li>{{jsxref("Statements/return", "return")}} ステートメント。この場合はジェネレーターの実行は終了し、 <code>IteratorResult</code> オブジェクトの <code>value</code> に <code>return</code> ステートメントで指定した値が、 <code>done</code> に <code>true</code> が代入されて呼び出し元に返されます。</li> +</ul> + +<p>ジェネレーターの <code>next()</code> メソッドにオプションの値が渡された場合、その値はジェネレーターの現在の <code>yield</code> 操作の返値となります。</p> + +<p>ジェネレーターのコードパス、 <code>yield</code> 演算子、新しい開始値を {{jsxref("Generator.prototype.next()")}} に渡すことで指定することができる機能により、ジェネレーターは大きな力と制御を提供します。</p> + +<h2 id="Examples" name="Examples">例</h2> + +<p>次のコードはジェネレーター関数の定義例です。</p> + +<pre class="brush: js">function* countAppleSales () { + let saleList = [3, 7, 5] + for (let i = 0; i < saleList.length; i++) { + yield saleList[i] + } +}</pre> + +<p>ジェネレーター関数が定義されると、ご覧のようにイテレーターを構築するために使用されます。</p> + +<pre class="brush: js">let appleStore = countAppleSales() // Generator { } +console.log(appleStore.next()) // { value: 3, done: false } +console.log(appleStore.next()) // { value: 7, done: false } +console.log(appleStore.next()) // { value: 5, done: false } +console.log(appleStore.next()) // { value: undefined, done: true }</pre> + +<h2 id="Specifications" name="Specifications">仕様書</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">仕様書</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#prod-YieldExpression', 'Yield')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">ブラウザーの互換性</h2> + +<div class="hidden">このページの互換性一覧表は構造化データから生成されています。データに協力していただけるのであれば、 <a class="external" href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> をチェックアウトしてプルリクエストを送信してください。</div> + +<p>{{Compat("javascript.operators.yield")}}</p> + +<h2 id="See_also" name="See_also">関連情報</h2> + +<ul> + <li><a href="/ja/docs/Web/JavaScript/Guide/The_Iterator_protocol">Iterator プロトコル</a></li> + <li>{{jsxref("Statements/function*", "function*")}}</li> + <li>{{jsxref("Operators/function*", "function* expression")}}</li> + <li>{{jsxref("Operators/yield*", "yield*")}}</li> +</ul> diff --git a/files/ja/web/javascript/reference/operators/yield_star_/index.html b/files/ja/web/javascript/reference/operators/yield_star_/index.html new file mode 100644 index 0000000000..e1aedb2d58 --- /dev/null +++ b/files/ja/web/javascript/reference/operators/yield_star_/index.html @@ -0,0 +1,140 @@ +--- +title: yield* +slug: Web/JavaScript/Reference/Operators/yield* +tags: + - ECMAScript 2015 + - Generators + - Iterable + - Iterator + - JavaScript + - Operator + - Reference + - yield* + - ジェネレーター + - 演算子 +translation_of: Web/JavaScript/Reference/Operators/yield* +--- +<div>{{jsSidebar("Operators")}}</div> + +<p><span class="seoSummary"><strong><code>yield*</code> 式</strong>は別の {{jsxref("Statements/function*", "ジェネレーター", "", 1)}} や反復可能なオブジェクトに委任するために使用されます。</span></p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-yieldasterisk.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"> yield* <var>expression</var>;</pre> + +<dl> + <dt><code><var>expression</var></code></dt> + <dd>反復可能なオブジェクトを返す式。</dd> +</dl> + +<h2 id="Description" name="Description">解説</h2> + +<p><code>yield*</code> 式はオペランドを反復し、それによって返されたそれぞれの値をもたらします。</p> + +<p><code>yield*</code> 式自体の値は、イテレーターが閉じたとき (つまり <code>done</code> が <code>true</code> のとき) に返される値です。</p> + +<h2 id="Examples" name="Examples">例</h2> + +<h3 id="Delegating_to_another_generator" name="Delegating_to_another_generator">別のジェネレータに委任する</h3> + +<p>次のコードでは、 <code>g1()</code> によってもたらされる値は、 <code>g2()</code> で得られているものと同じように <code>next()</code> の呼び出しから返されます。</p> + +<pre class="brush: js">function* g1() { + yield 2; + yield 3; + yield 4; +} + +function* g2() { + yield 1; + yield* g1(); + yield 5; +} + +const iterator = g2(); + +console.log(iterator.next()); // {value: 1, done: false} +console.log(iterator.next()); // {value: 2, done: false} +console.log(iterator.next()); // {value: 3, done: false} +console.log(iterator.next()); // {value: 4, done: false} +console.log(iterator.next()); // {value: 5, done: false} +console.log(iterator.next()); // {value: undefined, done: true} +</pre> + +<h3 id="Other_Iterable_objects" name="Other_Iterable_objects">他の反復可能なオブジェクト</h3> + +<p>ジェネレータオブジェクトのほかに、 <code>yield*</code> は他の種類の反復 (例えば、配列、文字列、 {{jsxref("Functions/arguments", "arguments")}} オブジェクト) を <code>yield</code> することができます。</p> + +<pre class="brush: js">function* g3() { + yield* [1, 2]; + yield* '34'; + yield* Array.from(arguments); +} + +const iterator = g3(5, 6); + +console.log(iterator.next()); // {value: 1, done: false} +console.log(iterator.next()); // {value: 2, done: false} +console.log(iterator.next()); // {value: "3", done: false} +console.log(iterator.next()); // {value: "4", done: false} +console.log(iterator.next()); // {value: 5, done: false} +console.log(iterator.next()); // {value: 6, done: false} +console.log(iterator.next()); // {value: undefined, done: true} +</pre> + +<h3 id="The_value_of_yield*_expression_itself" name="The_value_of_yield*_expression_itself"><code>yield*</code> 式自体の値</h3> + +<p><code>yield*</code> は式であり、文ではありません。そのため、値に評価されます。</p> + +<pre class="brush: js">function* g4() { + yield* [1, 2, 3]; + return 'foo'; +} + +function* g5() { + const g4ReturnValue = yield* g4(); + console.log(g4ReturnValue) // 'foo' + return g4ReturnValue; +} + +const iterator = g5(); + +console.log(iterator.next()); // {value: 1, done: false} +console.log(iterator.next()); // {value: 2, done: false} +console.log(iterator.next()); // {value: 3, done: false} done is false because g5 generator isn't finished, only g4 +console.log(iterator.next()); // {value: 'foo', done: true} +</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-generator-function-definitions-runtime-semantics-evaluation', 'Yield')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">ブラウザーの互換性</h2> + +<div class="hidden">このページの互換性一覧表は構造化データから生成されています。データに協力していただけるのであれば、 <a class="external" href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> をチェックアウトしてプルリクエストを送信してください。</div> + +<p>{{Compat("javascript.operators.yield_star")}}</p> + +<h2 id="See_also" name="See_also">関連情報</h2> + +<ul> + <li><a href="/ja/docs/Web/JavaScript/Guide/The_Iterator_protocol">Iterator プロトコル</a></li> + <li>{{jsxref("Statements/function*", "function*")}}</li> + <li>{{jsxref("Operators/function*", "function* expression")}}</li> + <li>{{jsxref("Operators/yield", "yield")}}</li> +</ul> |