diff options
author | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:43:23 -0500 |
---|---|---|
committer | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:43:23 -0500 |
commit | 218934fa2ed1c702a6d3923d2aa2cc6b43c48684 (patch) | |
tree | a9ef8ac1e1b8fe4207b6d64d3841bfb8990b6fd0 /files/zh-tw/web/javascript/reference/global_objects | |
parent | 074785cea106179cb3305637055ab0a009ca74f2 (diff) | |
download | translated-content-218934fa2ed1c702a6d3923d2aa2cc6b43c48684.tar.gz translated-content-218934fa2ed1c702a6d3923d2aa2cc6b43c48684.tar.bz2 translated-content-218934fa2ed1c702a6d3923d2aa2cc6b43c48684.zip |
initial commit
Diffstat (limited to 'files/zh-tw/web/javascript/reference/global_objects')
118 files changed, 20757 insertions, 0 deletions
diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/@@iterator/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/@@iterator/index.html new file mode 100644 index 0000000000..eb73724bef --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/@@iterator/index.html @@ -0,0 +1,89 @@ +--- +title: 'Array.prototype[@@iterator]()' +slug: Web/JavaScript/Reference/Global_Objects/Array/@@iterator +tags: + - Array + - ECMAScript 2015 + - Iterator + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/@@iterator +--- +<div>{{JSRef}}</div> + +<p><code><strong>@@iterator</strong></code> 屬性的初始值與 {{jsxref("Array.prototype.values()", "values()")}} 屬性的初始值為相同的的函式物件。</p> + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox"><code><var>arr</var>[Symbol.iterator]()</code></pre> + +<h3 id="回傳值">回傳值</h3> + +<p>陣列的<strong>迭代器(iterator)</strong>函式,預設與 {{jsxref("Array.prototype.values()", "values()")}} 函式相同。</p> + +<h2 id="範例">範例</h2> + +<h3 id="使用_for...of_迴圈進行迭代">使用 <code>for...of</code> 迴圈進行迭代</h3> + +<pre class="brush: js">var arr = ['w', 'y', 'k', 'o', 'p']; +var eArr = arr[Symbol.iterator](); +// your browser must support for..of loop +// and let-scoped variables in for loops +for (let letter of eArr) { + console.log(letter); +} +</pre> + +<h3 id="另一種迭代方式">另一種迭代方式</h3> + +<pre class="brush: js">var arr = ['w', 'y', 'k', 'o', 'p']; +var eArr = arr[Symbol.iterator](); +console.log(eArr.next().value); // w +console.log(eArr.next().value); // y +console.log(eArr.next().value); // k +console.log(eArr.next().value); // o +console.log(eArr.next().value); // p +</pre> + +<h2 id="規範">規範</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-array.prototype-@@iterator', 'Array.prototype[@@iterator]()')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype-@@iterator', 'Array.prototype[@@iterator]()')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.@@iterator")}}</p> +</div> + +<h2 id="參見">參見</h2> + +<ul> + <li>{{jsxref("Array.prototype.keys()")}}</li> + <li>{{jsxref("Array.prototype.entries()")}}</li> + <li>{{jsxref("Array.prototype.forEach()")}}</li> + <li>{{jsxref("Array.prototype.every()")}}</li> + <li>{{jsxref("Array.prototype.some()")}}</li> + <li>{{jsxref("Array.prototype.values()")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/concat/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/concat/index.html new file mode 100644 index 0000000000..c8fc9a7aca --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/concat/index.html @@ -0,0 +1,157 @@ +--- +title: Array.prototype.concat() +slug: Web/JavaScript/Reference/Global_Objects/Array/concat +tags: + - Array + - JavaScript + - Method + - Prototype + - Reference + - 陣列 +translation_of: Web/JavaScript/Reference/Global_Objects/Array/concat +--- +<div>{{JSRef}}</div> + +<p><code><strong>concat()</strong></code> 方法被用來合併兩個或多個陣列。此方法不會改變現有的陣列,回傳一個包含呼叫者陣列本身的值,作為代替的是回傳一個新陣列。</p> + +<div>{{EmbedInteractiveExample("pages/js/array-concat.html")}}</div> + + + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox">var <var>new_array</var> = <var>old_array</var>.concat(<var>value1</var>[, <var>value2</var>[, ...[, <var>valueN</var>]]])</pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>value<em>N</em></code></dt> + <dd>陣列以及/或者值,用來合併成一個新的陣列。請參閱下方詳細資訊描述。</dd> +</dl> + +<h3 id="回傳值">回傳值</h3> + +<p>一個新的{{jsxref("Array","陣列")}}實體。</p> + +<h2 id="描述">描述</h2> + +<p><code>concat</code> 產生一個由呼叫者陣列自己的元素,以及對每一個參數按照順序,合併參數的元素(如果參數是個陣列)或者是參數自己本身(如果參數不是一個陣列)成為一個新的陣列。<code>concat</code> 方法不會遞迴巢狀陣列參數。</p> + +<p><code>concat</code> 方法不會改變 <code>this</code> 自己本身或是任何被提供當做參數的陣列,取而代之則是回傳一個淺層複製(shallow copy)包含了與原始的陣列中一樣的元素的副本。原始陣列的元素被複製到新的陣列的規則如下所示:</p> + +<ul> + <li>物件參考(並非為實際的物件):<code>concat</code> 複製物件的參考至新的陣列。不管是原始的還是新的陣列都參考到相同的物件。也就是說,如果一個被參照的物件被修改了,變動會同時反映到新的以及原始的陣列中。</li> + <li>資料型態為字串、數值或是布林(非 {{jsxref("Global_Objects/String", "String")}}、{{jsxref("Global_Objects/Number", "Number")}} 及 {{jsxref("Global_Objects/Boolean", "Boolean")}} 物件):<code>concat</code> 複製字串及數值的值到新的陣列。</li> +</ul> + +<div class="note"> +<p><strong>備註:</strong>合併(多個)陣列/(多個)值將讓原始的陣列不會被受到影響。此外,任何對新陣列(只有在元素不是物件參考的情況下)的操作都不會影響原始的陣列,反之亦然。</p> +</div> + +<h2 id="範例">範例</h2> + +<h3 id="合併兩個陣列">合併兩個陣列</h3> + +<p>下面的程式碼為合併兩個陣列:</p> + +<pre class="brush: js">var alpha = ['a', 'b', 'c']; +var numeric = [1, 2, 3]; + +alpha.concat(numeric); +// 結果: ['a', 'b', 'c', 1, 2, 3] +</pre> + +<h3 id="合併三個陣列">合併三個陣列</h3> + +<p>下面的程式碼為合併三個陣列:</p> + +<pre class="brush: js">var num1 = [1, 2, 3], + num2 = [4, 5, 6], + num3 = [7, 8, 9]; + +var nums = num1.concat(num2, num3); + +console.log(nums); +// 結果:[1, 2, 3, 4, 5, 6, 7, 8, 9] +</pre> + +<h3 id="合併值到一個陣列">合併值到一個陣列</h3> + +<p>下面的程式碼為合併三個值到一個陣列中:</p> + +<pre class="brush: js">var alpha = ['a', 'b', 'c']; + +var alphaNumeric = alpha.concat(1, [2, 3]); + +console.log(alphaNumeric); +// 結果:['a', 'b', 'c', 1, 2, 3] +</pre> + +<h3 id="合併巢狀陣列">合併巢狀陣列</h3> + +<p>下面的程式碼為合併巢狀陣列,並證明保留了原本的參考(references):</p> + +<pre class="brush: js">var num1 = [[1]]; +var num2 = [2, [3]]; + +var nums = num1.concat(num2); + +console.log(nums); +// results in [[1], 2, [3]] + +// modify the first element of num1 +num1[0].push(4); + +console.log(nums); +// results in [[1, 4], 2, [3]] +</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('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>首次定義。實作於 JavaScript 1.2。</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.4', 'Array.prototype.concat')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.concat', 'Array.prototype.concat')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.concat', 'Array.prototype.concat')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.concat")}}</p> +</div> + +<h2 id="參見">參見</h2> + +<ul> + <li>{{jsxref("Array.push", "push")}} / {{jsxref("Array.pop", "pop")}} — 從陣列的尾端加入/移除元素</li> + <li>{{jsxref("Array.unshift", "unshift")}} / {{jsxref("Array.shift", "shift")}} — 從陣列的前端加入/移除元素</li> + <li>{{jsxref("Array.splice", "splice")}} — 從陣列特定的位置加入/移除元素</li> + <li>{{jsxref("String.prototype.concat()")}}</li> + <li>{{jsxref("Symbol.isConcatSpreadable")}} – 控制扁平化</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/copywithin/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/copywithin/index.html new file mode 100644 index 0000000000..30520215e3 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/copywithin/index.html @@ -0,0 +1,156 @@ +--- +title: Array.prototype.copyWithin() +slug: Web/JavaScript/Reference/Global_Objects/Array/copyWithin +tags: + - Array + - ECMAScript 2015 + - JavaScript + - Method + - Prototype + - Reference + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/copyWithin +--- +<div>{{JSRef}}</div> + +<p><code><strong>copyWithin()</strong></code> 方法會對陣列的一部分進行淺拷貝至同一陣列的另一位置並回傳此陣列,而不修改其大小。</p> + +<div>{{EmbedInteractiveExample("pages/js/array-copywithin.html")}}</div> + + + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox"><var>arr</var>.copyWithin(<var>target</var>) +<var>arr</var>.copyWithin(<var>target</var>, <var>start</var>) +<var>arr</var>.copyWithin(<var>target</var>, <var>start</var>, <var>end</var>) +</pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>target</code></dt> + <dd>要複製序列(sequence)至該位置的索引(起始為 0)。若為負數,<code>target</code> 將會自陣列末項開始計算。</dd> + <dd>假如 <code>target</code> 大於等於 <code>arr.length</code>,則沒有項目會被複製。如果 <code>target</code> 的索引在 <code>start</code> 之後,則拷貝的序列將會被修剪以符合 <code>arr.length</code>。</dd> + <dt><code>start</code> {{optional_inline}}</dt> + <dd>開始拷貝的起始元素索引(起始為 0)。若為負數,<code>start</code> 將會自陣列末項開始計算。</dd> + <dd>如果省略 <code>start</code>,<code>copyWithin</code> 將會自陣列首項開始複製(預設為 0)。</dd> + <dt><code>end</code> {{optional_inline}}</dt> + <dd>結束拷貝的結尾元素索引(起始為 0)。<code>copyWithin</code> 會拷貝至此索引,但不包含 <code>end</code>。若為負數,<code>end</code> 將會自陣列末項開始計算。</dd> + <dd>如果省略 <code>end</code>,<code>copyWithin</code> 將會一路拷貝至陣列末項(預設至 <code>arr.length</code>)。</dd> +</dl> + +<h3 id="回傳值">回傳值</h3> + +<p>被修改後的陣列。</p> + +<h2 id="描述">描述</h2> + +<p>The <code>copyWithin</code> works like C and C++'s <code>memmove</code>, and is a high-performance method to shift the data of an {{jsxref("Array")}}. This especially applies to the {{jsxref("TypedArray/copyWithin", "TypedArray")}} method of the same name. The sequence is copied and pasted as one operation; pasted sequence will have the copied values even when the copy and paste region overlap.</p> + +<p>The <code>copyWithin</code> function is intentionally <em>generic</em>, it does not require that its this value be an {{jsxref("Array")}} object.</p> + +<p>The <code>copyWithin</code> method is a mutable method. It does not alter the length of <code>this</code>, but will change its content and create new properties if necessary.</p> + +<h2 id="範例">範例</h2> + +<pre class="brush: js">[1, 2, 3, 4, 5].copyWithin(-2); +// [1, 2, 3, 1, 2] + +[1, 2, 3, 4, 5].copyWithin(0, 3); +// [4, 5, 3, 4, 5] + +[1, 2, 3, 4, 5].copyWithin(0, 3, 4); +// [4, 2, 3, 4, 5] + +[1, 2, 3, 4, 5].copyWithin(-2, -3, -1); +// [1, 2, 3, 3, 4] + +[].copyWithin.call({length: 5, 3: 1}, 0, 3); +// {0: 1, 3: 1, length: 5} + +// ES2015 Typed Arrays are subclasses of Array +var i32a = new Int32Array([1, 2, 3, 4, 5]); + +i32a.copyWithin(0, 2); +// Int32Array [3, 4, 5, 4, 5] + +// On platforms that are not yet ES2015 compliant: +[].copyWithin.call(new Int32Array([1, 2, 3, 4, 5]), 0, 3, 4); +// Int32Array [4, 2, 3, 4, 5] +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<pre class="brush: js">if (!Array.prototype.copyWithin) { + Array.prototype.copyWithin = + // Array: Number[, Number[, Number]] + function copyWithin(target, start, stop) { + var positiveT = target >= 0, + positiveS = (start = start | 0) >= 0, + length = this.length, + zero = 0, + r = function() {return ((+new Date) * Math.random()).toString(36)}, + delimiter = "\b" + r() + "-" + r() + "-" + r() + "\b", + hold; + + stop = stop || this.length; + hold = this.slice.apply(this, + positiveT? + [start, stop]: + positiveS? + [start, -target]: + [start]) + .join(delimiter); + + return this.splice.apply(this, + positiveT? + [target, stop - start, hold]: + positiveS? + [target, stop, hold]: + [target, start, hold]), + this.join(delimiter).split(delimiter).slice(zero, length); + } +} +</pre> + +<h2 id="規範">規範</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-array.prototype.copywithin', 'Array.prototype.copyWithin')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES2016', '#sec-array.prototype.copywithin', 'Array.prototype.copyWithin')}}</td> + <td>{{Spec2('ES2016')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.copywithin', 'Array.prototype.copyWithin')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.copyWithin")}}</p> +</div> + +<h2 id="參見">參見</h2> + +<ul> + <li>{{jsxref("Array")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/entries/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/entries/index.html new file mode 100644 index 0000000000..80c3f33e1f --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/entries/index.html @@ -0,0 +1,86 @@ +--- +title: Array.prototype.entries() +slug: Web/JavaScript/Reference/Global_Objects/Array/entries +tags: + - Array + - ECMAScript6 + - Iterator + - JavaScript + - Method + - Prototype + - 迭代器 + - 陣列 +translation_of: Web/JavaScript/Reference/Global_Objects/Array/entries +--- +<div>{{JSRef}}</div> + +<p><code><strong>entries()</strong></code> 方法會回傳一個包含陣列中每一個索引之鍵值對(key/value pairs)的新陣列迭代器(<code><strong>Array Iterator</strong></code>)物件。</p> + +<div>{{EmbedInteractiveExample("pages/js/array-entries.html")}}</div> + + + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox"><var>a</var>.entries()</pre> + +<h3 id="回傳值">回傳值</h3> + +<p>一個新的 {{jsxref("Array")}} 迭代器物件。</p> + +<h2 id="範例">範例</h2> + +<h3 id="使用_for…of_進行迭代">使用 <a href="/zh-TW/docs/Web/JavaScript/Reference/Statements/for...of">for…of</a> 進行迭代</h3> + +<pre class="brush:js">var a = ['a', 'b', 'c']; +var iterator = a.entries(); + +for (let e of iterator) { + console.log(e); +} +// [0, 'a'] +// [1, 'b'] +// [2, 'c'] +</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('ES2015', '#sec-array.prototype.entries', 'Array.prototype.entries')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>首次定義。</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.entries', 'Array.prototype.entries')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.entries")}}</p> +</div> + +<h2 id="參見">參見</h2> + +<ul> + <li>{{jsxref("Array.prototype.keys()")}}</li> + <li>{{jsxref("Array.prototype.values()")}}</li> + <li>{{jsxref("Array.prototype.forEach()")}}</li> + <li>{{jsxref("Array.prototype.every()")}}</li> + <li>{{jsxref("Array.prototype.some()")}}</li> + <li><a href="/zh-TW/docs/Web/JavaScript/Reference/Statements/for...of">for...of</a></li> + <li><a href="/zh-TW/docs/Web/JavaScript/Reference/Iteration_protocols">迭代協議</a></li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/every/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/every/index.html new file mode 100644 index 0000000000..3c0aa59938 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/every/index.html @@ -0,0 +1,191 @@ +--- +title: Array.prototype.every() +slug: Web/JavaScript/Reference/Global_Objects/Array/every +tags: + - Array + - ECMAScript 5 + - JavaScript + - Method + - Prototype + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/every +--- +<div>{{JSRef}}</div> + +<p><code><strong>every()</strong></code> 方法會測試陣列中的所有元素是否都通過了由給定之函式所實作的測試。</p> + +<div>{{EmbedInteractiveExample("pages/js/array-every.html")}}</div> + + + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox"><var>arr</var>.every(<var>callback</var>[, <var>thisArg</var>])</pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>callback</code></dt> + <dd>用來測試每一個元素的函式,它包含三個引數: + <dl> + <dt><code>currentValue</code>(必要的)</dt> + <dd>目前正要被處理的陣列元素。</dd> + <dt><code>index</code>(可選的)</dt> + <dd>目前正要被處理的陣列元素之索引值。</dd> + <dt><code>array</code>(可選的)</dt> + <dd>呼叫 <code>every</code> 的陣列。</dd> + </dl> + </dd> + <dt><code>thisArg</code></dt> + <dd>可選的。執行 <code>callback</code> 回呼函式的 <code>this</code> 值。</dd> +</dl> + +<h3 id="回傳值">回傳值</h3> + +<p>若回呼函式在處理每一個陣列元素時皆得到 {{Glossary("truthy")}} 值,則回傳 <code><strong>true</strong></code>。否則,回傳值為 <code><strong>false</strong></code>。</p> + +<h2 id="描述">描述</h2> + +<p>The <code>every</code> method executes the provided <code>callback</code> function once for each element present in the array until it finds one where <code>callback</code> returns a {{Glossary("falsy")}} value. If such an element is found, the <code>every</code> method immediately returns <code>false</code>. Otherwise, if <code>callback</code> returns a {{Glossary("truthy")}} value for all elements, <code>every</code> returns <code>true</code>. <code>callback</code> is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values.</p> + +<p><code>callback</code> is invoked with three arguments: the value of the element, the index of the element, and the Array object being traversed.</p> + +<p>If a <code>thisArg</code> parameter is provided to <code>every</code>, it will be used as callback's <code>this</code> value. Otherwise, the value <code>undefined</code> will be used as its <code>this</code> value. The <code>this</code> value ultimately observable by <code>callback</code> is determined according to <a href="/en-US/docs/Web/JavaScript/Reference/Operators/this">the usual rules for determining the <code>this</code> seen by a function</a>.</p> + +<p><code>every</code> does not mutate the array on which it is called.</p> + +<p>The range of elements processed by <code>every</code> is set before the first invocation of <code>callback</code>. Elements which are appended to the array after the call to <code>every</code> begins will not be visited by <code>callback</code>. If existing elements of the array are changed, their value as passed to <code>callback</code> will be the value at the time <code>every</code> visits them; elements that are deleted are not visited.</p> + +<p><code>every</code> acts like the "for all" quantifier in mathematics. In particular, for an empty array, it returns true. (It is <a href="http://en.wikipedia.org/wiki/Vacuous_truth#Vacuous_truths_in_mathematics">vacuously true</a> that all elements of the <a href="http://en.wikipedia.org/wiki/Empty_set#Common_problems">empty set</a> satisfy any given condition.)</p> + +<h2 id="範例">範例</h2> + +<h3 id="Testing_size_of_all_array_elements">Testing size of all array elements</h3> + +<p>The following example tests whether all elements in the array are bigger than 10.</p> + +<pre class="brush: js">function isBigEnough(element, index, array) { + return element >= 10; +} +[12, 5, 8, 130, 44].every(isBigEnough); // false +[12, 54, 18, 130, 44].every(isBigEnough); // true +</pre> + +<h3 id="Using_arrow_functions">Using arrow functions</h3> + +<p><a href="/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">Arrow functions</a> provide a shorter syntax for the same test.</p> + +<pre class="brush: js">[12, 5, 8, 130, 44].every(x => x >= 10); // false +[12, 54, 18, 130, 44].every(x => x >= 10); // true</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p><code>every</code> was added to the ECMA-262 standard in the 5th edition; as such it may not be present in other implementations of the standard. You can work around this by inserting the following code at the beginning of your scripts, allowing use of <code>every</code> in implementations which do not natively support it. This algorithm is exactly the one specified in ECMA-262, 5th edition, assuming <code>Object</code> and <code>TypeError</code> have their original values and that <code>callbackfn.call</code> evaluates to the original value of {{jsxref("Function.prototype.call")}}</p> + +<pre class="brush: js">if (!Array.prototype.every) { + Array.prototype.every = function(callbackfn, thisArg) { + 'use strict'; + var T, k; + + if (this == null) { + throw new TypeError('this is null or not defined'); + } + + // 1. Let O be the result of calling ToObject passing the this + // value as the argument. + var O = Object(this); + + // 2. Let lenValue be the result of calling the Get internal method + // of O with the argument "length". + // 3. Let len be ToUint32(lenValue). + var len = O.length >>> 0; + + // 4. If IsCallable(callbackfn) is false, throw a TypeError exception. + if (typeof callbackfn !== 'function') { + throw new TypeError(); + } + + // 5. If thisArg was supplied, let T be thisArg; else let T be undefined. + if (arguments.length > 1) { + T = thisArg; + } + + // 6. Let k be 0. + k = 0; + + // 7. Repeat, while k < len + while (k < len) { + + var kValue; + + // a. Let Pk be ToString(k). + // This is implicit for LHS operands of the in operator + // b. Let kPresent be the result of calling the HasProperty internal + // method of O with argument Pk. + // This step can be combined with c + // c. If kPresent is true, then + if (k in O) { + + // i. Let kValue be the result of calling the Get internal method + // of O with argument Pk. + kValue = O[k]; + + // ii. Let testResult be the result of calling the Call internal method + // of callbackfn with T as the this value and argument list + // containing kValue, k, and O. + var testResult = callbackfn.call(T, kValue, k, O); + + // iii. If ToBoolean(testResult) is false, return false. + if (!testResult) { + return false; + } + } + k++; + } + return true; + }; +} +</pre> + +<h2 id="規範">規範</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.16', 'Array.prototype.every')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.6.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.every', 'Array.prototype.every')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.every', 'Array.prototype.every')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.every")}}</p> +</div> + +<h2 id="參見">參見</h2> + +<ul> + <li>{{jsxref("Array.prototype.forEach()")}}</li> + <li>{{jsxref("Array.prototype.some()")}}</li> + <li>{{jsxref("TypedArray.prototype.every()")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/fill/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/fill/index.html new file mode 100644 index 0000000000..1a7d0f9f24 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/fill/index.html @@ -0,0 +1,156 @@ +--- +title: Array.prototype.fill() +slug: Web/JavaScript/Reference/Global_Objects/Array/fill +tags: + - Array + - ECMAScript 2015 + - JavaScript + - 原型 + - 填充工具 + - 方法 +translation_of: Web/JavaScript/Reference/Global_Objects/Array/fill +--- +<div>{{JSRef}}</div> + +<p><code><strong>fill()</strong></code> 方法會將陣列中索引的第一個到最後一個的每個位置全部填入一個靜態的值。</p> + +<div>{{EmbedInteractiveExample("pages/js/array-fill.html")}}</div> + + + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox"><var>arr</var>.fill(<var>value[</var>, <var>start[<var>, <var>end]]</var>)</var></var> +</pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>value</code></dt> + <dd>欲填入陣列的值。</dd> + <dt><code>start</code> {{optional_inline}}</dt> + <dd>起始的索引值,預設為 0。</dd> + <dt><code>end</code> {{optional_inline}}</dt> + <dd>結束的索引值,預設為 <code>this.length</code>(即陣列的長度)。</dd> +</dl> + +<h3 id="回傳值">回傳值</h3> + +<p>修改後的陣列。</p> + +<h2 id="說明">說明</h2> + +<p>要填入的元素區間為 [<code>start</code>, <code>end</code>),意即包含 <code>start</code> 但不包含 <code>end</code>。</p> + +<p><strong><code>fill</code></strong> 方法採用了三個傳入引數(arguments),分別為<code>value</code>、<code>start</code> 及 <code>end</code>。<code>start</code> 和 <code>end</code> 為可選引數,其預設值分別為 <code>0</code> 和 <code>this</code> 物件(該陣列)的 <code>length</code>。</p> + +<p>若 <code>start</code> 為負數,則此方法會將其換算成 <code>length+start</code>,<code>length</code> 即該陣列的長度。同理,若 <code>end</code> 為負數,其會被換算成 <code>length+end</code>。</p> + +<p><strong><code>fill</code></strong> 函式刻意地被設計成通用的函式,它不需要 <code>this</code> 物件一定是一個陣列物件。此外,它是可變動的(mutable)方法,意即會修改 <code>this</code> 物件本身並回傳,而非只是回傳拷貝。</p> + +<p>當 <strong><code>fill</code></strong> 方法獲得一個傳入的物件,會將傳入的物件位置進行複製,並把其參考值(reference)之拷貝填入陣列中。</p> + +<h2 id="範例">範例</h2> + +<pre class="brush: js">[1, 2, 3].fill(4); // [4, 4, 4] +[1, 2, 3].fill(4, 1); // [1, 4, 4] +[1, 2, 3].fill(4, 1, 2); // [1, 4, 3] +[1, 2, 3].fill(4, 1, 1); // [1, 2, 3] +[1, 2, 3].fill(4, 3, 3); // [1, 2, 3] +[1, 2, 3].fill(4, -3, -2); // [4, 2, 3] +[1, 2, 3].fill(4, NaN, NaN); // [1, 2, 3] +[1, 2, 3].fill(4, 3, 5); // [1, 2, 3] +Array(3).fill(4); // [4, 4, 4] +[].fill.call({ length: 3 }, 4); // {0: 4, 1: 4, 2: 4, length: 3} + +// Objects by reference. +var arr = Array(3).fill({}) // [{}, {}, {}]; +arr[0].hi = "hi"; // [{ hi: "hi" }, { hi: "hi" }, { hi: "hi" }] +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<pre class="brush: js">if (!Array.prototype.fill) { + Object.defineProperty(Array.prototype, 'fill', { + value: function(value) { + + // 步驟 1 - 2。 + if (this == null) { + throw new TypeError('this is null or not defined'); + } + + var O = Object(this); + + // 步驟 3 - 5。 + var len = O.length >>> 0; + + // 步驟 6 - 7。 + var start = arguments[1]; + var relativeStart = start >> 0; + + // 步驟 8。 + var k = relativeStart < 0 ? + Math.max(len + relativeStart, 0) : + Math.min(relativeStart, len); + + // 步驟 9 - 10。 + var end = arguments[2]; + var relativeEnd = end === undefined ? + len : end >> 0; + + // 步驟 11。 + var final = relativeEnd < 0 ? + Math.max(len + relativeEnd, 0) : + Math.min(relativeEnd, len); + + // 步驟 12。 + while (k < final) { + O[k] = value; + k++; + } + + // 步驟 13。 + return O; + } + }); +} +</pre> + +<p>如果你需要支援實際上棄用的 JavaScript 引擎且其不支援 <code><a href="/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty">Object.defineProperty</a></code> 的話,最好不要採用上述的工具來填充方法至 <code>Array.prototype</code>,因為你不能將這個方法設定為不可列舉(non-enumerable)的屬性。</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('ES2015', '#sec-array.prototype.fill', 'Array.prototype.fill')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>初次定義。</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.fill', 'Array.prototype.fill')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.fill")}}</p> +</div> + +<h2 id="參見">參見</h2> + +<ul> + <li>{{jsxref("Array")}}</li> + <li>{{jsxref("TypedArray.prototype.fill()")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/filter/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/filter/index.html new file mode 100644 index 0000000000..49546e6505 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/filter/index.html @@ -0,0 +1,238 @@ +--- +title: Array.prototype.filter() +slug: Web/JavaScript/Reference/Global_Objects/Array/filter +tags: + - Array + - ECMAScript 5 + - JavaScript + - 原型 + - 參見 + - 填充工具 + - 方法 +translation_of: Web/JavaScript/Reference/Global_Objects/Array/filter +--- +<div>{{JSRef}}</div> + +<p><code><strong>filter()</strong></code> 方法會建立一個經指定之函式運算後,由原陣列中通過該函式檢驗之元素所構成的新陣列。</p> + +<div>{{EmbedInteractiveExample("pages/js/array-filter.html")}}</div> + + + +<h3 id="ES6_版本">ES6 版本</h3> + +<pre class="brush: js">const words = ["spray", "limit", "elite", "exuberant", "destruction", "present", "happy"]; + +let longWords = words.filter(word => word.length > 6); + +// Filtered array longWords is ["exuberant", "destruction", "present"] +</pre> + +<h2 id="語法">語法</h2> + +<pre><var>var newArray = arr</var>.filter(<var>callback(element[, index[, array]])</var>[, <var>thisArg</var>])</pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>callback</code></dt> + <dd>此函式為一個斷言,用於測試陣列中的每個元素。回傳值為 <code>true</code> 時將當前的元素保留至新陣列中,若為 <code>false</code> 則不保留。可傳入三個參數:</dd> + <dd> + <dl> + <dt><code>element</code></dt> + <dd>原陣列目前所迭代處理中的元素。</dd> + <dt><code>index</code>{{optional_inline}}</dt> + <dd>原陣列目前所迭代處理中的元素之索引。</dd> + <dt><code>array</code>{{optional_inline}}</dt> + <dd>呼叫 <code>filter</code> 方法的陣列。</dd> + </dl> + </dd> + <dt><code>thisArg</code> {{optional_inline}}</dt> + <dd>可選的。執行 <code>callback</code> 回呼函式的 <code>this</code> 值。</dd> +</dl> + +<h3 id="回傳值">回傳值</h3> + +<p>一個元素為通過回呼函式檢驗的新陣列。</p> + +<h2 id="描述">描述</h2> + +<p><code>filter()</code> 會將所有陣列中的元素分別傳入一次至 <code>callback</code> 函式當中,並將所有傳入此回呼函式並得到回傳值為 <a href="/zh-TW/docs/Glossary/Truthy">Truthy</a> 的元素建構成一個新的陣列。<code>callback</code> 函式只會於陣列目前迭代之索引有指派值時被呼叫,回呼函式不會在該陣列索引已被刪除或從未被賦值時被調用。原始陣列中沒有通過 <code>callback</code> 檢驗的元素會被簡單的跳過,且不會被包含在新建立的陣列中。</p> + +<p><code>callback</code> 函式於被調用時會傳入三個參數:</p> + +<ol> + <li>元素值</li> + <li>元素之索引</li> + <li>被迭代的陣列物件</li> +</ol> + +<p>若有提供 <code>thisArg</code> 參數予 <code>filter</code> 方法,<code>thisArg</code> 將會被當作回呼函式的 <code>this</code> 值,否則 <code>this</code> 會是 <code>undefined</code>。<code>callback</code> 的最終 <code>this</code> 值是依據<a href="/zh-TW/docs/Web/JavaScript/Reference/Operators/this">函式的 <code>this</code> 規則</a>來決定。</p> + +<p><code>filter()</code> 不會修改呼叫它的原始陣列。</p> + +<p>由 <code>filter()</code> 方法所回傳之新陣列的範圍,於 <code>callback</code> 函式第一次被調用之前就已經被設定。而在呼叫 <code>filter()</code> 之後才加至原始陣列中的元素,將不會傳入 <code>callback</code> 當中。假如原始陣列中元素的值改變或被刪除了,則 <code>callback</code> 得到此元素的值將會是 <code>filter()</code> 傳入元素當下的值。而被刪除的原始陣列元素並不會被迭代到。</p> + +<h2 id="範例">範例</h2> + +<h3 id="過濾所有的小數字">過濾所有的小數字</h3> + +<p>以下範例會用 <code>filter()</code> 建立一個把所有小於 10 的元素都移掉的陣列。</p> + +<pre class="brush: js">function isBigEnough(value) { + return value >= 10; +} + +var filtered = [12, 5, 8, 130, 44].filter(isBigEnough); +// filtered is [12, 130, 44] +</pre> + +<h3 id="從_JSON_過濾無效的項目">從 JSON 過濾無效的項目</h3> + +<p>以下範例會用 <code>filter()</code> 建立一個把非零 numeric <code>id</code> 的元素都過濾掉的的 JSON。</p> + +<pre class="brush: js">var arr = [ + { id: 15 }, + { id: -1 }, + { id: 0 }, + { id: 3 }, + { id: 12.2 }, + { }, + { id: null }, + { id: NaN }, + { id: 'undefined' } +]; + +var invalidEntries = 0; + +function isNumber(obj) { + return obj!== undefined && typeof(obj) === 'number' && !isNaN(obj); +} + +function filterByID(item) { + if (isNumber(item.id)) { + return true; + } + invalidEntries++; + return false; +} + +var arrByID = arr.filter(filterByID); + +<code>console.log('過濾好的陣列\n', arrByID); +// 過濾好的陣列 +// [{ id: 15 }, { id: -1 }, { id: 0 }, { id: 3 }, { id: 12.2 }] + +console.log('無效的元素數量 = ', invalidEntries); +// 無效的元素數量 = 4</code></pre> + +<h3 id="在陣列中搜尋">在陣列中搜尋</h3> + +<p>下面範例使用 <code>filter()</code> 去過濾符合搜尋條件的陣列內容。</p> + +<pre class="brush: js">var fruits = ['apple', 'banana', 'grapes', 'mango', 'orange']; + +/** + * 陣列透過搜尋條件(查詢)過濾物件 + */ +function filterItems(query) { + return fruits.filter(function(el) { + return el.toLowerCase().indexOf(query.toLowerCase()) > -1; + }) +} + +console.log(filterItems('ap')); // ['apple', 'grapes'] +console.log(filterItems('an')); // ['banana', 'mango', 'orange']</pre> + +<h3 id="ES2015_實作方式">ES2015 實作方式</h3> + +<pre class="brush: js">const fruits = ['apple', 'banana', 'grapes', 'mango', 'orange']; + +/** + * 陣列透過搜尋條件(查詢)過濾物件 + */ +const filterItems = (query) => { + return fruits.filter((el) => + el.toLowerCase().indexOf(query.toLowerCase()) > -1 + ); +} + +console.log(filterItems('ap')); // ['apple', 'grapes'] +console.log(filterItems('an')); // ['banana', 'mango', 'orange'] + +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p><code>filter()</code> 在 ECMA-262 第五版時被納入標準;它也許不會出現在該標準的所有實作引擎之中。你可以在你的腳本最前面加入下面的程式碼作為替代方案,讓不支援 <code>filter()</code> 的 ECMA-262 實作引擎能夠使用它。假設 <code>fn.call</code> 是採用 {{jsxref("Function.prototype.bind()")}} 的原始值,這個演算法完全和 ECMA-262 第五版定義的規格相同。</p> + +<pre class="brush: js">if (!Array.prototype.filter) + Array.prototype.filter = function(func, thisArg) { + 'use strict'; + if ( ! ((typeof func === 'Function') && this) ) + throw new TypeError(); + + var len = this.length >>> 0, + res = new Array(len), // 預先配置陣列 + c = 0, i = -1; + if (thisArg === undefined) + while (++i !== len) + // 確認物件的鍵值i是否有被設置 + if (i in this) + if (func(t[i], i, t)) + res[c++] = t[i]; + else + while (++i !== len) + // 確認物件的鍵值i是否有被設置 + if (i in this) + if (func.call(thisArg, t[i], i, t)) + res[c++] = t[i]; + + res.length = c; // 將陣列縮至適當大小 + return res; + }; +</pre> + +<h2 id="規範">規範</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">規範</th> + <th scope="col">狀態</th> + <th scope="col">備註</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.20', 'Array.prototype.filter')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.6.</td> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-array.prototype.filter', 'Array.prototype.filter')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.filter', 'Array.prototype.filter')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.filter")}}</p> +</div> + +<h2 id="參見">參見</h2> + +<ul> + <li>{{jsxref("Array.prototype.forEach()")}}</li> + <li>{{jsxref("Array.prototype.every()")}}</li> + <li>{{jsxref("Array.prototype.some()")}}</li> + <li>{{jsxref("Array.prototype.reduce()")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/find/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/find/index.html new file mode 100644 index 0000000000..0db7e05a3c --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/find/index.html @@ -0,0 +1,204 @@ +--- +title: Array.prototype.find() +slug: Web/JavaScript/Reference/Global_Objects/Array/find +translation_of: Web/JavaScript/Reference/Global_Objects/Array/find +--- +<div>{{JSRef}}</div> + +<p><code><strong>find()</strong></code> 方法會回傳第一個滿足所提供之測試函式的元素<strong>值</strong>。否則回傳 {{jsxref("undefined")}}。</p> + +<div>{{EmbedInteractiveExample("pages/js/array-find.html")}}</div> + + + +<p>也可以參考 {{jsxref("Array.findIndex", "findIndex()")}} 方法,它回傳被找到的元素在陣列中的<strong>索引</strong>,而不是它的值。</p> + +<p>If you need to find the position of an element or whether an element exists in an array, use {{jsxref("Array.prototype.indexOf()")}} or {{jsxref("Array.prototype.includes()")}}.</p> + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox"><var>arr</var>.find(<var>callback</var>[, <var>thisArg</var>])</pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>callback</code></dt> + <dd>會處理陣列中每個元素的函數,它使用三個參數: + <dl> + <dt><code>element</code></dt> + <dd>在陣列中正被處理的元素。</dd> + <dt><code>index</code>{{optional_inline}}</dt> + <dd>在陣列中正被處理的元素的索引。</dd> + <dt><code>array</code>{{optional_inline}}</dt> + <dd>呼叫 <code>find</code> 的陣列。</dd> + </dl> + </dd> + <dt><code>thisArg</code> <code>{{Optional_inline}}</code></dt> + <dd>執行 <code>callback</code> 函式時被當作 <code>this</code> 的物件。</dd> +</dl> + +<h3 id="回傳值">回傳值</h3> + +<p>若元素通過測試則為其值;否則為 {{jsxref("undefined")}}。</p> + +<h2 id="描述">描述</h2> + +<p><code>find</code> 方法會對每個元素執行一次 <code>callback</code> 函式,直到找到一個讓 <code>callback</code> 函式回傳 true 的元素。當元素被找到的時候,<code>find</code> 會立刻回傳該元素,否則 <code>find</code> 會回傳 {{jsxref("undefined")}}。<code>callback</code> 會被使用於陣列索引自 <code>0</code> 至 <code>length - 1</code>,並會被用於每一個的陣列索引,而不僅是那些有賦值的索引。這代表此方法在稀疏陣列(sparse arrays)上的效能可能較其他只存取已賦值索引的方法來的差。</p> + +<p><code>callback</code> 函式被呼叫時會傳入三個參數:元素的值、元素索引,以及正被迭代的陣列物件。</p> + +<p>如果提供 <code>thisArg</code> 參數予 <code>find</code>,其將會被當作 <code>callback</code> 每次被呼叫的 <code>this</code>。若是沒提供,則會使用 {{jsxref("undefined")}}。</p> + +<p><code>find</code> 並不會改變呼叫該方法的陣列。</p> + +<p>The range of elements processed by <code>find</code> is set before the first invocation of <code>callback</code>. Elements that are appended to the array after the call to <code>find</code> begins will not be visited by <code>callback</code>. If an existing, unvisited element of the array is changed by <code>callback</code>, its value passed to the visiting <code>callback</code> will be the value at the time that <code>find</code> visits that element's index; elements that are deleted are still visited.</p> + +<h2 id="範例">範例</h2> + +<h3 id="Find_an_object_in_an_array_by_one_of_its_properties">Find an object in an array by one of its properties</h3> + +<pre class="brush: js">var inventory = [ + {name: 'apples', quantity: 2}, + {name: 'bananas', quantity: 0}, + {name: 'cherries', quantity: 5} +]; + +function isCherries(fruit) { + return fruit.name === 'cherries'; +} + +console.log(inventory.find(isCherries)); +// { name: 'cherries', quantity: 5 }</pre> + +<h3 id="在陣列中找質數">在陣列中找質數</h3> + +<p>以下範例在陣列中找出一個屬於質數的元素,如果裡面不含質數則回傳 {{jsxref("undefined")}}。</p> + +<pre class="brush: js">function isPrime(element, index, array) { + var start = 2; + while (start <= Math.sqrt(element)) { + if (element % start++ < 1) { + return false; + } + } + return element > 1; +} + +console.log([4, 6, 8, 12].find(isPrime)); // undefined, not found +console.log([4, 5, 8, 12].find(isPrime)); // 5 +</pre> + +<p>The following examples show that non-existent and deleted elements are visited and that the value passed to the callback is their value when visited.</p> + +<pre class="brush: js">// Declare array with no element at index 2, 3 and 4 +var a = [0,1,,,,5,6]; + +// Shows all indexes, not just those that have been assigned values +a.find(function(value, index) { + console.log('Visited index ' + index + ' with value ' + value); +}); + +// Shows all indexes, including deleted +a.find(function(value, index) { + + // Delete element 5 on first iteration + if (index == 0) { + console.log('Deleting a[5] with value ' + a[5]); + delete a[5]; + } + // Element 5 is still visited even though deleted + console.log('Visited index ' + index + ' with value ' + value); +}); + +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p>這個方法在 ECMAScript 2015 中首次被規範,可能尚未在所有 JavaScript 應用中被實作。你可以使用以下程式片段來 polyfill <code>Array.prototype.find</code>:</p> + +<pre class="brush: js">// https://tc39.github.io/ecma262/#sec-array.prototype.find +if (!Array.prototype.find) { + Object.defineProperty(Array.prototype, 'find', { + value: function(predicate) { + // 1. Let O be ? ToObject(this value). + if (this == null) { + throw new TypeError('"this" is null or not defined'); + } + + var o = Object(this); + + // 2. Let len be ? ToLength(? Get(O, "length")). + var len = o.length >>> 0; + + // 3. If IsCallable(predicate) is false, throw a TypeError exception. + if (typeof predicate !== 'function') { + throw new TypeError('predicate must be a function'); + } + + // 4. If thisArg was supplied, let T be thisArg; else let T be undefined. + var thisArg = arguments[1]; + + // 5. Let k be 0. + var k = 0; + + // 6. Repeat, while k < len + while (k < len) { + // a. Let Pk be ! ToString(k). + // b. Let kValue be ? Get(O, Pk). + // c. Let testResult be ToBoolean(? Call(predicate, T, « kValue, k, O »)). + // d. If testResult is true, return kValue. + var kValue = o[k]; + if (predicate.call(thisArg, kValue, k, o)) { + return kValue; + } + // e. Increase k by 1. + k++; + } + + // 7. Return undefined. + return undefined; + } + }); +} +</pre> + +<p>If you need to support truly obsolete JavaScript engines that don't support <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty">Object.defineProperty</a></code>, it's best not to polyfill <code>Array.prototype</code> methods at all, as you can't make them non-enumerable.</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('ES6', '#sec-array.prototype.find', 'Array.prototype.find')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>首次定義</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.find', 'Array.prototype.find')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.find")}}</p> +</div> + +<h2 id="參見">參見</h2> + +<ul> + <li>{{jsxref("Array.prototype.findIndex()")}} – find and return an index</li> + <li>{{jsxref("Array.prototype.includes()")}} – test whether a value exists in the array</li> + <li>{{jsxref("Array.prototype.filter()")}} – find all matching elements</li> + <li>{{jsxref("Array.prototype.every()")}} – test all elements together</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/findindex/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/findindex/index.html new file mode 100644 index 0000000000..4271ae9ef1 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/findindex/index.html @@ -0,0 +1,181 @@ +--- +title: Array.prototype.findIndex() +slug: Web/JavaScript/Reference/Global_Objects/Array/findIndex +tags: + - Array + - ECMAScript 2015 + - JavaScript + - Method + - Prototype + - Reference + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/findIndex +--- +<div>{{JSRef}}</div> + +<p><code><strong>findIndex()</strong></code> 方法將依據提供的測試函式,尋找陣列中符合的元素,並返回其 <strong>index</strong>(索引)。如果沒有符合的對象,將返回 -1 。</p> + +<div>{{EmbedInteractiveExample("pages/js/array-findindex.html")}}</div> + + + +<div> </div> + +<p>另請參見 {{jsxref("Array.find", "find()")}} 方法,它返回陣列中找到的元素的<strong>值</strong>,而不是其索引。</p> + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox"><var>arr</var>.findIndex(<var>callback</var>[, <var>thisArg</var>])</pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>callback</code></dt> + <dd>針對陣列中的每個元素,都會執行該回呼函式,執行時會自動傳入下面三個參數: + <dl> + <dt><code>element</code></dt> + <dd>當前元素。</dd> + <dt><code>index</code>{{optional_inline}}</dt> + <dd>當前元素的索引。</dd> + <dt><code>array</code>{{optional_inline}}</dt> + <dd>呼叫 <code>findIndex</code> 的陣列。</dd> + </dl> + </dd> + <dt><code>thisArg</code>{{optional_inline}}</dt> + <dd>可選的。執行 <strong>callback</strong> 時作為 this 對象的值。</dd> +</dl> + +<h3 id="回傳值">回傳值</h3> + +<p>An index in the array if an element passes the test; otherwise, <strong>-1</strong>.</p> + +<h2 id="描述">描述</h2> + +<p><code>findIndex</code> 方法對陣列中的每一個索引:<code>0..length-1</code>(含)的元素執行一次 <code>callback</code> 直到有一個 <code>callback</code> 返回 truthy 值(一個可強制轉型(coerces)為 <code>true</code> 的值)。如果找到了一個這樣的元素,則 <code>findIndex</code> 將會立刻返回此次迭代的索引。若回呼函式從未回傳一個 truthy 值,或陣列的 <code>length</code> 為 0,則 <code>findIndex</code> 將會返回 -1。不像其他的陣列方法如 <code>some</code> 那樣,於稀疏(sparse)陣列上 <code>callback</code> <strong>仍會</strong>被呼叫,即使該索引的項目在陣列中並不存在。</p> + +<p><code>callback</code> 被呼叫時會傳入三個參數:元素的值、元素的索引,以及被迭代的陣列物件。</p> + +<p>如果一個 <code>thisArg</code> 參數被提供給 <code>findIndex</code>,它將會被當作 <code>this</code> 使用在每次回呼函式被調用的時候。如果沒有被提供,將會使用 {{jsxref("undefined")}}。</p> + +<p><code>findIndex</code> 不會修改呼叫此方法的陣列。</p> + +<p>在第一次呼叫 <code>callback</code> 函式時會確定元素的索引範圍,因此在 <code>findIndex</code> 方法開始執行之後添加到陣列的新元素將不會被 <code>callback</code> 函式訪問到。如果陣列中一個尚未被 <code>callback</code> 函式訪問到的元素的值被 <code>callback</code> 函式所改變,那麼當 <code>callback</code> 函式訪問到它時,它的值是將是根據它在陣列中的索引所訪問到的當前值;被刪除的元素仍然會被訪問到。</p> + +<h2 id="範例">範例</h2> + +<h3 id="尋找陣列中首個質數元素的索引">尋找陣列中首個質數元素的索引</h3> + +<p>以下的範例演示了如何查找一個陣列中首個質數元素的索引,找不到則返回 -1。</p> + +<pre class="brush: js">function isPrime(element, index, array) { + var start = 2; + while (start <= Math.sqrt(element)) { + if (element % start++ < 1) { + return false; + } + } + return element > 1; +} + +console.log([4, 6, 8, 12].findIndex(isPrime)); // -1, not found +console.log([4, 6, 7, 12].findIndex(isPrime)); // 2 +</pre> + +<h3 id="使用箭頭函式尋找索引">使用箭頭函式尋找索引</h3> + +<p>以下範例為使用箭頭函式尋找水果的索引。</p> + +<pre class="brush: js">const fruits = ["apple", "banana", "cantaloupe", "blueberries", "grapefruit"]; + +const index = fruits.findIndex(fruit => fruit === "blueberries"); + +console.log(index); // 3 +console.log(fruits[index]); // blueberries +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<pre class="brush: js">// https://tc39.github.io/ecma262/#sec-array.prototype.findIndex +if (!Array.prototype.findIndex) { + Object.defineProperty(Array.prototype, 'findIndex', { + value: function(predicate) { + // 1. Let O be ? ToObject(this value). + if (this == null) { + throw new TypeError('"this" is null or not defined'); + } + + var o = Object(this); + + // 2. Let len be ? ToLength(? Get(O, "length")). + var len = o.length >>> 0; + + // 3. If IsCallable(predicate) is false, throw a TypeError exception. + if (typeof predicate !== 'function') { + throw new TypeError('predicate must be a function'); + } + + // 4. If thisArg was supplied, let T be thisArg; else let T be undefined. + var thisArg = arguments[1]; + + // 5. Let k be 0. + var k = 0; + + // 6. Repeat, while k < len + while (k < len) { + // a. Let Pk be ! ToString(k). + // b. Let kValue be ? Get(O, Pk). + // c. Let testResult be ToBoolean(? Call(predicate, T, « kValue, k, O »)). + // d. If testResult is true, return k. + var kValue = o[k]; + if (predicate.call(thisArg, kValue, k, o)) { + return k; + } + // e. Increase k by 1. + k++; + } + + // 7. Return -1. + return -1; + } + }); +} +</pre> + +<p>如果您需要相容過時的不支援 <code><a href="/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty">Object.defineProperty</a></code> 的 JavaScript 引擎,最好不要使用 polyfill 來填充 <code>Array.prototype</code> 方法,因為無法使它們成為不可枚舉的(non-enumerable)屬性。</p> + +<h2 id="規範">規範</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-array.prototype.findindex', 'Array.prototype.findIndex')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.findIndex', 'Array.prototype.findIndex')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.findIndex")}}</p> +</div> + +<h2 id="參見">參見</h2> + +<ul> + <li>{{jsxref("Array.prototype.find()")}}</li> + <li>{{jsxref("Array.prototype.indexOf()")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/flat/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/flat/index.html new file mode 100644 index 0000000000..8a6a4b2549 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/flat/index.html @@ -0,0 +1,148 @@ +--- +title: Array.prototype.flat() +slug: Web/JavaScript/Reference/Global_Objects/Array/flat +tags: + - JavaScript + - 實驗中 + - 方法 + - 陣列 +translation_of: Web/JavaScript/Reference/Global_Objects/Array/flat +--- +<div>{{JSRef}} {{SeeCompatTable}}</div> + +<p><code><strong>flat()</strong></code> 函數以遞迴方式將特定深度的子陣列重新串接成為一新的陣列</p> + +<p class="hidden">\{{EmbedInteractiveExample("pages/js/array-flatten.html")}}</p> + + + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox"><var>var newArray = arr</var>.flat(<em>[depth]</em>);</pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>depth</code> {{optional_inline}}</dt> + <dd>指定巢狀陣列展開的深度。預設為1。</dd> +</dl> + +<h3 id="回傳值">回傳值</h3> + +<p>函數將會回傳一個由原先陣列的子陣列串接而成的新陣列。</p> + + + +<h2 id="範例">範例</h2> + +<h3 id="展開巢狀陣列">展開巢狀陣列</h3> + +<pre class="brush: js">var arr1 = [1, 2, [3, 4]]; +arr1.flat(); +// [1, 2, 3, 4] + +var arr2 = [1, 2, [3, 4, [5, 6]]]; +arr2.flat(); +// [1, 2, 3, 4, [5, 6]] + +var arr3 = [1, 2, [3, 4, [5, 6]]]; +arr3.flat(2); +// [1, 2, 3, 4, 5, 6]</pre> + +<h3 id="當遭遇空元素時">當遭遇空元素時</h3> + +<p>flat()函數會自動清除陣列中空的元素</p> + +<pre class="brush: js">var arr4 = [1, 2, , 4, 5]; +arr4.flat(); +// [1, 2, 4, 5] +</pre> + +<h2 id="替代方案">替代方案</h2> + +<h3 id="reduce_與_concat"><code>reduce</code> 與 <code>concat</code></h3> + +<pre class="brush: js">var arr1 = [1, 2, [3, 4]]; +arr1.flat(); + +//展開單層陣列 +arr1.reduce((acc, val) => acc.concat(val), []);// [1, 2, 3, 4] +</pre> + + + +<pre class="brush: js">//欲展開更深層的巢狀結構請使用reduce與concat的遞迴 +function flattenDeep(arr1) { + return arr1.reduce((acc, val) => Array.isArray(val) ? acc.concat(flattenDeep(val)) : acc.concat(val), []); +} +flattenDeep(arr1);// [1, 2, 3, 1, 2, 3, 4, 2, 3, 4] +</pre> + + + +<pre class="brush: js">//使用stack來實作非遞迴的展開 +var arr1 = [1,2,3,[1,2,3,4, [2,3,4]]]; +function flatten(input) { + const stack = [...input]; + const res = []; + while (stack.length) { + // pop value from stack + const next = stack.pop(); + if (Array.isArray(next)) { + // push back array items, won't modify the original input + stack.push(...next); + } else { + res.push(next); + } + } + //reverse to restore input order + return res.reverse(); +} +flatten(arr1);// [1, 2, 3, 1, 2, 3, 4, 2, 3, 4] +</pre> + +<pre><code>// 递归版本的反嵌套 +function flatten(array) { + var flattend = []; + (function flat(array) { + array.forEach(function(el) { + if (Array.isArray(el)) flat(el); + else flattend.push(el); + }); + })(array); + return flattend; +}</code></pre> + +<h2 id="規範">規範</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td><a href="https://tc39.github.io/proposal-flatMap/#sec-Array.prototype.flat"><code>Array.prototype.flat</code> proposal</a></td> + <td>Candidate (3)</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.flat")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Array.prototype.flatMap()")}}</li> + <li>{{jsxref("Array.prototype.map()")}}</li> + <li>{{jsxref("Array.prototype.reduce()")}}</li> + <li>{{jsxref("Array.prototype.concat()")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/foreach/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/foreach/index.html new file mode 100644 index 0000000000..df1dc91684 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/foreach/index.html @@ -0,0 +1,297 @@ +--- +title: Array.prototype.forEach() +slug: Web/JavaScript/Reference/Global_Objects/Array/forEach +tags: + - Array + - ECMAScript 5 + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/forEach +--- +<div>{{JSRef}}</div> + +<p><code><strong>forEach()</strong></code> 方法會將陣列內的每個元素,皆傳入並執行給定的函式一次。</p> + +<div>{{EmbedInteractiveExample("pages/js/array-foreach.html")}}</div> + + + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox"><var>arr</var>.forEach(function <var>callback(currentValue[, index[, array]]) { + //your iterator +}</var>[, <var>thisArg</var>]);</pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>callback</code></dt> + <dd>這個 callback 函式將會把 Array 中的每一個元素作為參數,帶進本 callback 函式裡,每個元素各執行一次,接收三個參數: + <dl> + <dt><code>currentValue</code></dt> + <dd>代表目前被處理中的 Array 之中的那個元素。</dd> + <dt><code>index</code>{{optional_inline}}</dt> + <dd>代表目前被處理中的 Array 之中的那個元素的index.</dd> + <dt><code>array</code>{{optional_inline}}</dt> + <dd>呼叫 <code>forEach()</code> 方法的那個 Array 本身,也就是上面語法中的 arr。</dd> + </dl> + </dd> + <dt><code>thisArg</code> {{Optional_inline}}</dt> + <dd>執行 <code>callback</code> 回呼函式的 <code><strong>this</strong></code>(即參考之 <code>Object</code>)值。</dd> +</dl> + +<h3 id="回傳值">回傳值</h3> + +<p>{{jsxref("undefined")}}。</p> + +<h2 id="描述">描述</h2> + +<p><code>forEach()</code> executes the provided <code>callback</code> once for each element present in the array in ascending order. It is not invoked for index properties that have been deleted or are uninitialized (i.e. on sparse arrays).</p> + +<p><code>callback</code> is invoked with <strong>three arguments</strong>:</p> + +<ul> + <li>the <strong>element value</strong></li> + <li>the <strong>element index</strong></li> + <li>the <strong>array being traversed</strong></li> +</ul> + +<p>If a <code>thisArg</code> parameter is provided to <code>forEach()</code>, it will be used as callback's <code>this</code> value. Otherwise, the value {{jsxref("undefined")}} will be used as its <code>this</code> value. The <code>this</code> value ultimately observable by <code>callback</code> is determined according to <a href="/zh-TW/docs/Web/JavaScript/Reference/Operators/this">the usual rules for determining the <code>this</code> seen by a function</a>.</p> + +<p>The range of elements processed by <code>forEach()</code> is set before the first invocation of <code>callback</code>. Elements that are appended to the array after the call to <code>forEach()</code> begins will not be visited by <code>callback</code>. If the values of existing elements of the array are changed, the value passed to <code>callback</code> will be the value at the time <code>forEach()</code> visits them; elements that are deleted before being visited are not visited. If elements that are already visited are removed (e.g. using {{jsxref("Array.prototype.shift()", "shift()")}}) during the iteration, later elements will be skipped - see example below.</p> + +<p><code>forEach()</code> executes the <code>callback</code> function once for each array element; unlike {{jsxref("Array.prototype.map()", "map()")}} or {{jsxref("Array.prototype.reduce()", "reduce()")}} it always returns the value {{jsxref("undefined")}} and is not chainable. The typical use case is to execute side effects at the end of a chain.</p> + +<p><code>forEach()</code> does not mutate the array on which it is called (although <code>callback</code>, if invoked, may do so).</p> + +<div class="note"> +<p>除非是拋出異常,否則並沒有中止 <code>forEach()</code> 迴圈的辦法。如果你需要這樣做,<code>forEach()</code> 就是錯誤的用法,相反的,應該要用簡單的迴圈。如果你要測試陣列裡面的元素並回傳布林值,可以用 {{jsxref("Array.prototype.every()", "every()")}} 或 {{jsxref("Array.prototype.some()", "some()")}}。如果可以的話,新的方法 {{jsxref("Array.prototype.find()", "find()")}} 或 {{jsxref("Array.prototype.findIndex()", "findIndex()")}} 也可以用於 true 值之後提前終止。</p> +</div> + +<h2 id="範例">範例</h2> + +<h3 id="Converting_from_for_to_forEach">Converting from for to forEach</h3> + +<p>before</p> + +<pre class="brush:js">const items = ['item1', 'item2', 'item3']; +const copy = []; + +for (let i=0; i<items.length; i++) { + copy.push(items[i]) +} +</pre> + +<p>after</p> + +<pre class="brush:js">const items = ['item1', 'item2', 'item3']; +const copy = []; + +items.forEach(function(item){ + copy.push(item) +}); + +</pre> + +<p> </p> + +<h3 id="Printing_the_contents_of_an_array">Printing the contents of an array</h3> + +<p>The following code logs a line for each element in an array:</p> + +<pre class="brush:js">function logArrayElements(element, index, array) { + console.log('a[' + index + '] = ' + element); +} + +// Notice that index 2 is skipped since there is no item at +// that position in the array. +[2, 5, , 9].forEach(logArrayElements); +// logs: +// a[0] = 2 +// a[1] = 5 +// a[3] = 9 +</pre> + +<h3 id="Using_thisArg">Using <code>thisArg</code></h3> + +<p>The following (contrived) example updates an object's properties from each entry in the array:</p> + +<pre class="brush:js">function Counter() { + this.sum = 0; + this.count = 0; +} +Counter.prototype.add = function(array) { + array.forEach(function(entry) { + this.sum += entry; + ++this.count; + }, this); + // ^---- Note +}; + +const obj = new Counter(); +obj.add([2, 5, 9]); +obj.count; +// 3 +obj.sum; +// 16 +</pre> + +<p>Since the <code>thisArg</code> parameter (<code>this</code>) is provided to <code>forEach()</code>, it is passed to <code>callback</code> each time it's invoked, for use as its <code>this</code> value.</p> + +<div class="note"> +<p>If passing the function argument using an <a href="/zh-TW/docs/Web/JavaScript/Reference/Functions/Arrow_functions">arrow function expression</a> the <code>thisArg</code> parameter can be omitted as arrow functions lexically bind the {{jsxref("Operators/this", "this")}} value.</p> +</div> + +<h3 id="An_object_copy_function">An object copy function</h3> + +<p>The following code creates a copy of a given object. There are different ways to create a copy of an object; the following is just one way and is presented to explain how <code>Array.prototype.forEach()</code> works by using ECMAScript 5 <code>Object.*</code> meta property functions.</p> + +<pre class="brush: js">function copy(obj) { + const copy = Object.create(Object.getPrototypeOf(obj)); + const propNames = Object.getOwnPropertyNames(obj); + + propNames.forEach(function(name) { + const desc = Object.getOwnPropertyDescriptor(obj, name); + Object.defineProperty(copy, name, desc); + }); + + return copy; +} + +const obj1 = { a: 1, b: 2 }; +const obj2 = copy(obj1); // obj2 looks like obj1 now +</pre> + +<h3 id="If_the_array_is_modified_during_iteration_other_elements_might_be_skipped.">If the array is modified during iteration, other elements might be skipped.</h3> + +<p>The following example logs "one", "two", "four". When the entry containing the value "two" is reached, the first entry of the whole array is shifted off, which results in all remaining entries moving up one position. Because element "four" is now at an earlier position in the array, "three" will be skipped. <code>forEach()</code> does not make a copy of the array before iterating.</p> + +<pre class="brush:js">var words = ['one', 'two', 'three', 'four']; +words.forEach(function(word) { + console.log(word); + if (word === 'two') { + words.shift(); + } +}); +// one +// two +// four +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p><code>forEach()</code> was added to the ECMA-262 standard in the 5th edition; as such it may not be present in other implementations of the standard. You can work around this by inserting the following code at the beginning of your scripts, allowing use of <code>forEach()</code> in implementations that don't natively support it. This algorithm is exactly the one specified in ECMA-262, 5th edition, assuming {{jsxref("Object")}} and {{jsxref("TypeError")}} have their original values and that <code>callback.call()</code> evaluates to the original value of {{jsxref("Function.prototype.call()")}}.</p> + +<pre class="brush: js">// Production steps of ECMA-262, Edition 5, 15.4.4.18 +// Reference: http://es5.github.io/#x15.4.4.18 +if (!Array.prototype.forEach) { + + Array.prototype.forEach = function(callback/*, thisArg*/) { + + var T, k; + + if (this == null) { + throw new TypeError('this is null or not defined'); + } + + // 1. Let O be the result of calling toObject() passing the + // |this| value as the argument. + var O = Object(this); + + // 2. Let lenValue be the result of calling the Get() internal + // method of O with the argument "length". + // 3. Let len be toUint32(lenValue). + var len = O.length >>> 0; + + // 4. If isCallable(callback) is false, throw a TypeError exception. + // See: http://es5.github.com/#x9.11 + if (typeof callback !== 'function') { + throw new TypeError(callback + ' is not a function'); + } + + // 5. If thisArg was supplied, let T be thisArg; else let + // T be undefined. + if (arguments.length > 1) { + T = arguments[1]; + } + + // 6. Let k be 0. + k = 0; + + // 7. Repeat while k < len. + while (k < len) { + + var kValue; + + // a. Let Pk be ToString(k). + // This is implicit for LHS operands of the in operator. + // b. Let kPresent be the result of calling the HasProperty + // internal method of O with argument Pk. + // This step can be combined with c. + // c. If kPresent is true, then + if (k in O) { + + // i. Let kValue be the result of calling the Get internal + // method of O with argument Pk. + kValue = O[k]; + + // ii. Call the Call internal method of callback with T as + // the this value and argument list containing kValue, k, and O. + callback.call(T, kValue, k, O); + } + // d. Increase k by 1. + k++; + } + // 8. return undefined. + }; +} +</pre> + +<h2 id="規範">規範</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.18', 'Array.prototype.forEach')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.6.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.foreach', 'Array.prototype.forEach')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.foreach', 'Array.prototype.forEach')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.forEach")}}</p> +</div> + +<h2 id="參見">參見</h2> + +<ul> + <li>{{jsxref("Array.prototype.find()")}}</li> + <li>{{jsxref("Array.prototype.findIndex()")}}</li> + <li>{{jsxref("Array.prototype.map()")}}</li> + <li>{{jsxref("Array.prototype.every()")}}</li> + <li>{{jsxref("Array.prototype.some()")}}</li> + <li>{{jsxref("Map.prototype.forEach()")}}</li> + <li>{{jsxref("Set.prototype.forEach()")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/from/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/from/index.html new file mode 100644 index 0000000000..229b92f5e6 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/from/index.html @@ -0,0 +1,215 @@ +--- +title: Array.from() +slug: Web/JavaScript/Reference/Global_Objects/Array/from +tags: + - Array + - ECMAScript 2015 + - JavaScript + - Method + - Reference + - polyfill + - 陣列 +translation_of: Web/JavaScript/Reference/Global_Objects/Array/from +--- +<div>{{JSRef}}</div> + +<p><code><strong>Array.from()</strong></code> 方法會從類陣列(array-like)或是可迭代(iterable)物件建立一個新的 <code>Array</code> 實體。</p> + +<div>{{EmbedInteractiveExample("pages/js/array-from.html")}}</div> + + + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>arrayLike</code></dt> + <dd>將類陣列或可迭代物件轉換成陣列</dd> + <dt><code>mapFn {{Optional_inline}}</code></dt> + <dd>Map 函式走訪陣列中的每一個元素。</dd> + <dt><code>thisArg {{Optional_inline}}</code></dt> + <dd><code>mapFn</code> 函式執行時的 <code>this</code> 對象。</dd> +</dl> + +<h3 id="回傳值">回傳值</h3> + +<p>一個新的 {{jsxref("Array")}} 實體。</p> + +<h2 id="描述">描述</h2> + +<p><code>Array.from()</code> 讓你從這些物件建立陣列:</p> + +<ul> + <li>類陣列(array-like)物件(物件具有 <code>length</code> 屬性以及索引化(indexed)的元素)或</li> + <li><a href="/zh-TW/docs/Web/JavaScript/Guide/iterable">可迭代物件</a>(物件具有可以讓你利用迭代的方式取得它自己本身的元素,像是 {{jsxref("Map")}} 和 {{jsxref("Set")}})。</li> +</ul> + +<p><code>Array.from()</code> 有個可選用的參數 <code>mapFn</code>,它允許你在建立出新的陣列實體之後,可以接著對陣列(或是其子類別物件)中的每一個元素執行 {{jsxref("Array.prototype.map", "map")}} 函式。更清楚地說,<code> Array.from(obj, mapFn, thisArg)</code> 跟 <code>Array.from(obj).map(mapFn, thisArg)</code> 的結果是一樣的,除非所建立的不是一個可用的中介陣列(intermediate array)。這對於某些陣列的子類別來說就很重要,例如<a href="/zh-TW/docs/Web/JavaScript/Typed_arrays">型別陣列</a>,因為中介陣列必須要把內容值做一番截頭去尾的操作來讓它們變成適合的物件型態。</p> + +<p><code>from()</code> 方法的 <code>length</code> 屬性值為 1。</p> + +<p>在 ES2015,類別語法允許原生內建的物件以及使用者自定義的物件可以被子類別化(sub-classing);因此,靜態方法像是 <code>Array.from</code>,是「繼承」了 <code>Array</code> 的子類別後,然後建立新的子類別的實體,而不是建立 <code>Array</code> 本身。</p> + +<h2 id="範例">範例</h2> + +<h3 id="從字串產生陣列">從字串產生陣列</h3> + +<pre class="brush: js">Array.from('foo'); +// ["f", "o", "o"]</pre> + +<h3 id="從集合產生陣列">從集合產生陣列</h3> + +<pre class="brush: js">var s = new Set(['foo', window]); +Array.from(s); +// ["foo", window]</pre> + +<h3 id="從映射產生陣列">從映射產生陣列</h3> + +<pre class="brush: js">var m = new Map([[1, 2], [2, 4], [4, 8]]); +Array.from(m); +// [[1, 2], [2, 4], [4, 8]]</pre> + +<h3 id="從類陣列物件(arguments)產生陣列">從類陣列物件(arguments)產生陣列</h3> + +<pre class="brush: js">function f() { + return Array.from(arguments); +} + +f(1, 2, 3); + +// [1, 2, 3]</pre> + +<h3 id="使用箭頭函式及_Array.from">使用箭頭函式及 <code>Array.from</code></h3> + +<pre class="brush: js">// 使用箭頭函式作為 map 函式來 +// 操作元素 +Array.from([1, 2, 3], x => x + x); +// [2, 4, 6] + +// 產生數值序列 +// 因為陣列中的每個位置都會被初始化為 `undefined`, +// 下方 `v` 會是 `undefined` +Array.from({length: 5}, (v, i) => i); +// [0, 1, 2, 3, 4] +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p><code>Array.from</code> 在 ECMA-262 標準第六版(ES2015)被加入;在某些實作可能尚未被支援。你可以將下面的程式碼插入到妳的 script 的最前面,如果你使用的工作環境不具有原生支援 <code>Array.from</code> 的能力。這個演算法根據 ECMA-262 第六版中的規範實現,假定 <code>Object</code> 及 <code>TypeError</code> 它們本身已具有值且 <code>callback.call</code> 對應到原本 {{jsxref("Function.prototype.call")}} 的值。除此之外,因為 Polyfill 無法實現真正的迭代,這個實作不支援 ECMA-262 第六版中所定義的泛型迭代。</p> + +<pre class="brush: js">// Production steps of ECMA-262, Edition 6, 22.1.2.1 +if (!Array.from) { + Array.from = (function () { + var toStr = Object.prototype.toString; + var isCallable = function (fn) { + return typeof fn === 'function' || toStr.call(fn) === '[object Function]'; + }; + var toInteger = function (value) { + var number = Number(value); + if (isNaN(number)) { return 0; } + if (number === 0 || !isFinite(number)) { return number; } + return (number > 0 ? 1 : -1) * Math.floor(Math.abs(number)); + }; + var maxSafeInteger = Math.pow(2, 53) - 1; + var toLength = function (value) { + var len = toInteger(value); + return Math.min(Math.max(len, 0), maxSafeInteger); + }; + + // The length property of the from method is 1. + return function from(arrayLike/*, mapFn, thisArg */) { + // 1. Let C be the this value. + var C = this; + + // 2. Let items be ToObject(arrayLike). + var items = Object(arrayLike); + + // 3. ReturnIfAbrupt(items). + if (arrayLike == null) { + throw new TypeError('Array.from requires an array-like object - not null or undefined'); + } + + // 4. If mapfn is undefined, then let mapping be false. + var mapFn = arguments.length > 1 ? arguments[1] : void undefined; + var T; + if (typeof mapFn !== 'undefined') { + // 5. else + // 5. a If IsCallable(mapfn) is false, throw a TypeError exception. + if (!isCallable(mapFn)) { + throw new TypeError('Array.from: when provided, the second argument must be a function'); + } + + // 5. b. If thisArg was supplied, let T be thisArg; else let T be undefined. + if (arguments.length > 2) { + T = arguments[2]; + } + } + + // 10. Let lenValue be Get(items, "length"). + // 11. Let len be ToLength(lenValue). + var len = toLength(items.length); + + // 13. If IsConstructor(C) is true, then + // 13. a. Let A be the result of calling the [[Construct]] internal method + // of C with an argument list containing the single item len. + // 14. a. Else, Let A be ArrayCreate(len). + var A = isCallable(C) ? Object(new C(len)) : new Array(len); + + // 16. Let k be 0. + var k = 0; + // 17. Repeat, while k < len… (also steps a - h) + var kValue; + while (k < len) { + kValue = items[k]; + if (mapFn) { + A[k] = typeof T === 'undefined' ? mapFn(kValue, k) : mapFn.call(T, kValue, k); + } else { + A[k] = kValue; + } + k += 1; + } + // 18. Let putStatus be Put(A, "length", len, true). + A.length = len; + // 20. Return A. + return A; + }; + }()); +} +</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('ES2015', '#sec-array.from', 'Array.from')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>首次定義。</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.from', 'Array.from')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.from")}}</p> +</div> + +<h2 id="參見">參見</h2> + +<ul> + <li>{{jsxref("Array")}}</li> + <li>{{jsxref("Array.prototype.map()")}}</li> + <li>{{jsxref("TypedArray.from()")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/includes/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/includes/index.html new file mode 100644 index 0000000000..6d3d0e0cb2 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/includes/index.html @@ -0,0 +1,175 @@ +--- +title: Array.prototype.includes() +slug: Web/JavaScript/Reference/Global_Objects/Array/includes +tags: + - Array + - JavaScript + - Method + - Prototype + - Reference + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/includes +--- +<div>{{JSRef}}</div> + +<p><code><strong>includes()</strong></code> 方法會判斷陣列是否包含特定的元素,並以此來回傳 <code>true</code> 或 <code>false</code>。</p> + +<div>{{EmbedInteractiveExample("pages/js/array-includes.html")}}</div> + + + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox"><var>arr</var>.includes(<var>searchElement[</var>, <var>fromIndex]</var>) +</pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>searchElement</code></dt> + <dd>要搜尋的元素。</dd> + <dt><code>fromIndex</code> {{optional_inline}}</dt> + <dd>要於此陣列中開始搜尋 <code>searchElement</code> 的位置。如為負數值,則自 <code>array.length + fromIndex</code> 開始向後搜尋。預設值為 0。</dd> +</dl> + +<h3 id="回傳值">回傳值</h3> + +<p>布林值({{jsxref("Boolean")}})。</p> + +<h2 id="範例">範例</h2> + +<pre class="brush: js">[1, 2, 3].includes(2); // true +[1, 2, 3].includes(4); // false +[1, 2, 3].includes(3, 3); // false +[1, 2, 3].includes(3, -1); // true +[1, 2, NaN].includes(NaN); // true +</pre> + +<h3 id="fromIndex_大於或等於陣列長度"><code>fromIndex</code> 大於或等於陣列長度</h3> + +<p>如果 <code>fromIndex</code>大於或等於陣列長度, 會回傳<code>false</code>. 此陣列將不會被搜尋.</p> + +<pre class="brush: js">var arr = ['a', 'b', 'c']; + +arr.includes('c', 3); // false +arr.includes('c', 100); // false</pre> + +<h3 id="Computed_index_is_less_than_0">Computed index is less than 0</h3> + +<p>If <code>fromIndex</code> is negative, the computed index is calculated to be used as a position in the array at which to begin searching for <code>searchElement</code>. If the computed index is less than 0, the entire array will be searched.</p> + +<pre class="brush: js">// array length is 3 +// fromIndex is -100 +// computed index is 3 + (-100) = -97 + +var arr = ['a', 'b', 'c']; + +arr.includes('a', -100); // true +arr.includes('b', -100); // true +arr.includes('c', -100); // true</pre> + +<h3 id="includes_used_as_a_generic_method"><code>includes()</code> used as a generic method</h3> + +<p><code>includes()</code> method is intentionally generic. It does not require <code>this</code> value to be an Array object, so it can be applied to other kinds of objects (e.g. array-like objects). The example below illustrates <code>includes()</code> method called on the function's <a href="/en-US/docs/Web/JavaScript/Reference/Functions/arguments">arguments</a> object.</p> + +<pre class="brush: js">(function() { + console.log([].includes.call(arguments, 'a')); // true + console.log([].includes.call(arguments, 'd')); // false +})('a','b','c');</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<pre class="brush: js">// https://tc39.github.io/ecma262/#sec-array.prototype.includes +if (!Array.prototype.includes) { + Object.defineProperty(Array.prototype, 'includes', { + value: function(searchElement, fromIndex) { + + if (this == null) { + throw new TypeError('"this" is null or not defined'); + } + + // 1. Let O be ? ToObject(this value). + var o = Object(this); + + // 2. Let len be ? ToLength(? Get(O, "length")). + var len = o.length >>> 0; + + // 3. If len is 0, return false. + if (len === 0) { + return false; + } + + // 4. Let n be ? ToInteger(fromIndex). + // (If fromIndex is undefined, this step produces the value 0.) + var n = fromIndex | 0; + + // 5. If n ≥ 0, then + // a. Let k be n. + // 6. Else n < 0, + // a. Let k be len + n. + // b. If k < 0, let k be 0. + var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0); + + function sameValueZero(x, y) { + return x === y || (typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y)); + } + + // 7. Repeat, while k < len + while (k < len) { + // a. Let elementK be the result of ? Get(O, ! ToString(k)). + // b. If SameValueZero(searchElement, elementK) is true, return true. + if (sameValueZero(o[k], searchElement)) { + return true; + } + // c. Increase k by 1. + k++; + } + + // 8. Return false + return false; + } + }); +} +</pre> + +<p>If you need to support truly obsolete JavaScript engines that don't support <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty">Object.defineProperty</a></code>, it's best not to polyfill <code>Array.prototype</code> methods at all, as you can't make them non-enumerable.</p> + +<h2 id="規範">規範</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES7', '#sec-array.prototype.includes', 'Array.prototype.includes')}}</td> + <td>{{Spec2('ES7')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.includes', 'Array.prototype.includes')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.includes")}}</p> +</div> + +<h2 id="參見">參見</h2> + +<ul> + <li>{{jsxref("TypedArray.prototype.includes()")}}</li> + <li>{{jsxref("String.prototype.includes()")}}</li> + <li>{{jsxref("Array.prototype.indexOf()")}}</li> + <li>{{jsxref("Array.prototype.find()")}}</li> + <li>{{jsxref("Array.prototype.findIndex()")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/index.html new file mode 100644 index 0000000000..fe344c1811 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/index.html @@ -0,0 +1,457 @@ +--- +title: Array +slug: Web/JavaScript/Reference/Global_Objects/Array +tags: + - Array + - JavaScript + - NeedsTranslation + - TopicStub + - 陣列 +translation_of: Web/JavaScript/Reference/Global_Objects/Array +--- +<div>{{JSRef}}</div> + +<p>JavaScript 中的 <strong><code>Array</code></strong> 全域物件被用於建構陣列;陣列為高階(high-level)、似列表(list-like)的物件。陣列在Javascript 裡面並沒有固定的長度與型別。由於陣列的長度可以隨時被改變,所以並不能保證陣列的密度。這取決於開發者如何使用陣列。一般來說,這是個非常方便的特性,但如果這並不適用於你的開發工作,你也許會考慮使用型別陣列。</p> + +<p><strong>建立陣列</strong></p> + +<pre class="brush: js">var fruits = ['Apple', 'Banana']; + +console.log(fruits.length); +// 2 +</pre> + +<p><strong>(透過索引)取得陣列項目</strong></p> + +<pre class="brush: js">var first = fruits[0]; +// Apple + +var last = fruits[fruits.length - 1]; +// Banana +</pre> + +<p><strong>迭代陣列</strong></p> + +<pre class="brush: js">fruits.forEach(function(item, index, array) { + console.log(item, index); +}); +// Apple 0 +// Banana 1 +</pre> + +<p><strong>加入項目至陣列末端</strong></p> + +<pre class="brush: js">var newLength = fruits.push('Orange'); +// ["Apple", "Banana", "Orange"] +</pre> + +<p><strong>移除陣列末端項目</strong></p> + +<pre class="brush: js">var last = fruits.pop(); // 移除 <code>(</code>最末端的<code>) </code>Orange +// ["Apple", "Banana"]; +</pre> + +<p><strong>移除陣列前端項目</strong></p> + +<pre class="brush: js"><code>var first = fruits.shift(); // 移除 (最前端的) Apple +// ["Banana"];</code></pre> + +<p><strong>加入項目至陣列前端</strong></p> + +<pre class="brush: js">var newLength = fruits.unshift('Strawberry') // 加到陣列前端 +// ["Strawberry", "Banana"]; +</pre> + +<p><strong>在陣列中尋找項目的索引</strong></p> + +<pre class="brush: js">fruits.push('Mango'); +// ["Strawberry", "Banana", "Mango"] + +var pos = fruits.indexOf('Banana'); +// 1 +</pre> + +<p><strong>移除指定索引位置的項目</strong></p> + +<pre class="brush: js">var removedItem = fruits.splice(pos, 1); // 移除 pos 起的 1 個項目 + +// ["Strawberry", "Mango"]</pre> + +<p><strong>移除指定索引位置起的多個項目</strong></p> + +<pre class="brush: js">var vegetables = ['Cabbage', 'Turnip', 'Radish', 'Carrot']; +console.log(vegetables); +// ["Cabbage", "Turnip", "Radish", "Carrot"] + +var pos = 1, n = 2; + +var removedItems = vegetables.splice(pos, n); +// 這就是移除項目的方式, +// n 表示從該位置 (pos) 開始,一直到陣列的尾端有多少項目需要移除 + +console.log(vegetables); +// ["Cabbage", "Carrot"] (原始的陣列被改變) + +console.log(removedItems); +// ["Turnip", "Radish"]</pre> + +<p><strong>複製陣列</strong></p> + +<pre class="brush: js">var shallowCopy = fruits.slice(); // 這就是複製陣列的方式 +// ["Strawberry", "<code>Mango</code>"] +</pre> + +<h2 id="Syntax" name="Syntax">語法</h2> + +<pre class="syntaxbox">[<var>element0</var>, <var>element1</var>, ..., <var>elementN</var>] +new Array(<var>element0</var>, <var>element1</var>[, ...[, <var>elementN</var>]]) +new Array(<var>arrayLength</var>)</pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>element<em>N</em></code></dt> + <dd>除了只傳遞一個參數給 <code>Array</code> 構造函數,且該參數為一個數字的情況(詳見下方的 arrayLength 參數),JavaScript 陣列會以傳入的元素進行初始化。</dd> + <dd>請注意,這種特殊情況僅適用於以 <code>Array </code>構造函數建立的 JavaScript 陣列,而不適用於以括號語法建立的陣列常值(Array Literals)。</dd> + <dt><code>arrayLength</code></dt> + <dd>如果傳遞給 <code>Array</code> 構造函數的唯一參數是 0 和 2<sup>32</sup>-1(含)之間的整數,將回傳一個新的 JavaScript 陣列,其長度被設定為這個數字。如果參數是任何其他數值,將拋出 {{jsxref("RangeError")}} 異常。</dd> +</dl> + +<h2 id="Description" name="Description">說明</h2> + +<p>Array(「陣列」)是類似列表(list)的物件(Object),它們的原型(Prototype)擁有方法(methods)來執行遍歷和變異操作。JavaScript 陣列的長度(元素數量),以及其元素的類型都不是固定的。取決於工程師如何選擇使用陣列,可以隨時更改陣列的長度,也可不連續儲存資料, 所以並不保證這些資料是集中的。一般情況下,這些特性很方便使用;但若這些功能都不符合您的用途,您可能會想使用型別陣列(typed arrays)。</p> + +<p>有些人認為即便會發生警告,仍然<a class="external" href="http://www.andrewdupont.net/2006/05/18/javascript-associative-arrays-considered-harmful/">不應該使用關聯陣列</a>,而應該使用 {{jsxref("Global_Objects/Object", "objects")}}。您可參考<a class="external" href="http://www.less-broken.com/blog/2010/12/lightweight-javascript-dictionaries.html">輕量級 JavaScript 字典</a>當中的範例。</p> + +<h3 id="Accessing_array_elements" name="Accessing_array_elements">存取陣列元素</h3> + +<p>JavaScript 陣列是 zero-indexed:陣列元素的索引值編排從 0 開始,而最後一個元素的索引值等同於陣列的 {{jsxref("Array.length", "length")}} 屬性減 1。</p> + +<pre class="brush: js">var arr = ['this is the first element', 'this is the second element']; +console.log(arr[0]); // 紀錄出 'this is the first element' +console.log(arr[1]); // 記錄出 'this is the second element' +console.log(arr[arr.length - 1]); // 記錄出 'this is the second element' +</pre> + +<p>Array 元素同時也是物件的屬性,與 <code>toString</code> 是一種屬性相同。但若要透過下面這種方式存取陣列元素,因為屬性名稱無效的關係,會發生語法錯誤:</p> + +<pre class="brush: js">console.log(arr.0); // 語法錯誤 +</pre> + +<p>會造成如此的原因沒有什麼特別的,在 JavaScript 當中無法用小數點的方式來參照一個名稱開頭為數字的屬性,而必須括號的表示方式來存取。舉例來說,若您有個物件的屬性名稱為「<code>3d</code>」,就只能用括號的方式來參照。</p> + +<p>請看下列範例:</p> + +<pre class="brush: js">var years = [1950, 1960, 1970, 1980, 1990, 2000, 2010]; +console.log(years.0); // 語法錯誤 +console.log(years[0]); // 程式正常 +</pre> + +<pre class="brush: js">renderer.3d.setTexture(model, 'character.png'); // 語法錯誤 +renderer['3d'].setTexture(model, 'character.png'); // 程式正常 +</pre> + +<p>注意:以這個 <code>'3d'</code> 例子來說,必須用引號將 <code>3d</code> 包起來。您也可以將 JavaScript 陣列的索引用引號包起來(例如使用 <code>years['2']</code> 而不用 <code>years[2]</code>),但這不是必要的。JavaScript 會透過隱含的 <code>toString</code>,將 <code>years[2]</code> 當中的 2 強制轉換為字串。由於這個原因,<code>'2'</code> 與 <code>'02'</code> 會參照到 <code>years</code> 物件中的不同項目,下列程式範例結果可能回傳 <code>true</code>:</p> + +<pre class="brush: js">console.log(years['2'] != years['02']); +</pre> + +<p>另一種類似的情況是,物件屬性剛好與保留字(!)相同的情況。這種情況下僅能透過括號表示方式當中的字串常值來存取:</p> + +<pre class="brush: js">var promise = { + 'var' : 'text', + 'array': [1, 2, 3, 4] +}; + +console.log(promise['var']); +</pre> + +<h3 id="Relationship_between_length_and_numerical_properties" name="Relationship_between_length_and_numerical_properties"><code>length</code> 與數值屬性的關係</h3> + +<p>JavaScript 陣列的 {{jsxref("Array.length", "length")}} 屬性和其數值屬性相關。許多陣列的方法被呼叫時會參考 {{jsxref("Array.length", "length")}} 屬性的值(例如 {{jsxref("Array.join", "join")}}、{{jsxref("Array.slice", "slice")}}、{{jsxref("Array.indexOf", "indexOf")}} 等)。而有另一些方法則會去改變 {{jsxref("Array.length", "length")}} 屬性的值,如 {{jsxref("Array.push", "push")}}、{{jsxref("Array.splice", "splice")}}。</p> + +<pre class="brush: js">var fruits = []; +fruits.push('banana', 'apple', 'peach'); + +console.log(fruits.length); // 3 +</pre> + +<p>如果給陣列設定一個數值屬性,其值為有效但超過當下範圍的陣列 index,JavaScript 引擎會依照此數值更新陣列的 {{jsxref("Array.length", "length")}} 屬性:</p> + +<pre class="brush: js">fruits[5] = 'mango'; +console.log(fruits[5]); // 'mango' +console.log(Object.keys(fruits)); // ['0', '1', '2', '5'] +console.log(fruits.length); // 6 +</pre> + +<p>提高 {{jsxref("Array.length", "length")}} 屬性。</p> + +<pre class="brush: js">fruits.length = 10; +console.log(Object.keys(fruits)); // ['0', '1', '2', '5'] +console.log(fruits.length); // 10 +</pre> + +<div> +<p>降低 {{jsxref("Array.length", "length")}} 屬性則會刪除陣列元素。</p> + +<pre class="brush: js">fruits.length = 2; +console.log(Object.keys(fruits)); // ['0', '1'] +console.log(fruits.length); // 2 +</pre> + +<p>在 {{jsxref("Array.length")}} 頁面裡有進一步解釋。</p> +</div> + +<h3 id="Creating_an_array_using_the_result_of_a_match" name="Creating_an_array_using_the_result_of_a_match">使用 match 回傳結果來建立陣列</h3> + +<p>在字串與正規表示式之間的比對結果會產生一個 javascript 陣列。此陣列內含關於比對資訊的屬性與元素。 這樣的陣列由{{jsxref("RegExp.exec")}}, {{jsxref("String.match")}}, 和 {{jsxref("String.replace")}} 所產生。參考以下範例和表格,會有助於說明這些屬性和元素:</p> + +<pre class="brush: js">// 比對一個字元 d,後面接著一或多個 b,再接著一個 d +// Remember matched b's and the following d +// 忽略大小寫 + +var myRe = /d(b+)(d)/i; +var myArray = myRe.exec('cdbBdbsbz'); +</pre> + +<p>這項比對結果的屬性與元素參考如下:</p> + +<table class="fullwidth-table"> + <tbody> + <tr> + <td class="header">屬性/元素</td> + <td class="header">說明</td> + <td class="header">範例</td> + </tr> + <tr> + <td><code>input</code></td> + <td>唯讀屬性,代表 正規表示式用以比對的原始字串。</td> + <td>cdbBdbsbz</td> + </tr> + <tr> + <td><code>index</code></td> + <td>唯讀屬性,代表在字串中比對得到的索引,是以零為基礎(從0開始)。</td> + <td>1</td> + </tr> + <tr> + <td><code>[0]</code></td> + <td>一個唯獨元素以表示最後符合的字串</td> + <td>dbBd</td> + </tr> + <tr> + <td><code>[1], ...[n]</code></td> + <td>Read-only elements that specify the parenthesized substring matches, if included in the regular expression. The number of possible parenthesized substrings is unlimited.</td> + <td>[1]: bB<br> + [2]: d</td> + </tr> + </tbody> +</table> + +<h2 id="Properties" name="Properties">屬性</h2> + +<dl> + <dt>Array.length</dt> + <dd><code>Array</code> 建構子的長度為 1。</dd> + <dt>{{jsxref("Array.@@species", "get Array[@@species]")}}</dt> + <dd>用來建立衍生物件的建構函數。</dd> + <dt>{{jsxref("Array.prototype")}}</dt> + <dd>可加入屬性至所有陣列物件。</dd> +</dl> + +<h2 id="Methods" name="Methods">方法</h2> + +<dl> + <dt>{{jsxref("Array.from()")}}</dt> + <dd>用類似陣列或可列舉物件,來建立新的 <code>Array</code> 實例。</dd> + <dt>{{jsxref("Array.isArray()")}}</dt> + <dd>若變數是陣列就回傳 true,否則回傳 false。</dd> + <dt>{{jsxref("Array.of()")}}</dt> + <dd>用可變數量的引數來建立新的 <code>Array</code> 實例,不論引數的數量或型別。</dd> +</dl> + +<h2 id="Array_instances" name="Array_instances"><code>Array</code> 實例</h2> + +<p>所有的陣列實例都繼承自 {{jsxref("Array.prototype")}}。若修改這個陣列建構子 (Array constructor) 的原型物件 (prototype object),將會影響所有的陣列實體。</p> + +<h3 id="Methods_of_array_instances" name="Methods_of_array_instances">屬性</h3> + +<div>{{page('/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Properties')}}</div> + +<h3 id="Methods_of_array_instances" name="Methods_of_array_instances">方法</h3> + +<h4 id="Mutator_methods" name="Mutator_methods">Mutator methods</h4> + +<div>{{page('zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Mutator_methods')}}</div> + +<h4 id="Accessor_methods" name="Accessor_methods">Accessor methods</h4> + +<div>{{page('zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Accessor_methods')}}</div> + +<h4 id="Iteration_methods" name="Iteration_methods">Iteration methods</h4> + +<div>{{page('zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Iteration_methods')}}</div> + +<h2 id="Array_泛型方法"><code>Array</code> 泛型方法</h2> + +<div class="warning"> +<p><strong>泛型陣列並非標準且已被棄用,將會在不久之後被去除。</strong> </p> +</div> + +<p>有時你想將陣列方法用於字串或其他類陣列物件(像是函數 {{jsxref("Functions/arguments", "arguments", "", 1)}})。藉此操作,你將此字串視為由字元組成的陣列(反之為將其他非陣列視為物件)。如範例,若要確認字串中的每個字元是不是字母,你可能會這樣寫:</p> + +<pre class="brush: js">function isLetter(character) { + return character >= 'a' && character <= 'z'; +} + +if (Array.prototype.every.call(str, isLetter)) { + console.log("The string '" + str + "' contains only letters!"); +} +</pre> + +<p>這種表示法相當浪費,JavaScript 1.6 導入了一個通用方法:</p> + +<pre class="brush: js">if (Array.every(str, isLetter)) { + console.log("The string '" + str + "' contains only letters!"); +} +</pre> + +<p>{{jsxref("Global_Objects/String", "Generics", "#String_generic_methods", 1)}} 也同樣可用於 {{jsxref("String")}}.</p> + +<p>這<strong>並非 </strong>ECMAScript 的標準,且不被非 Gecko 引擎的瀏覽器支援。你應該將你的物件用 {{jsxref("Array.from()")}} 轉為陣列,以標準替代原有的方法;雖然此方法可能不被舊的瀏覽器所支援:</p> + +<pre class="brush: js">if (Array.from(str).every(isLetter)) { + console.log("The string '" + str + "' contains only letters!"); +} +</pre> + +<h2 id="Examples" name="Examples">範例</h2> + +<h3 id="Example_Creating_an_array" name="Example:_Creating_an_array">範例:建立陣列</h3> + +<p>以下範例會產生長度為 0 的 <code>msgArray</code> 陣列,然後指派字串值到 <code>msgArray[0]</code> 及 <code>msgArray[99]</code>,使陣列的長度變為 100。</p> + +<pre class="brush: js">var msgArray = []; +msgArray[0] = 'Hello'; +msgArray[99] = 'world'; + +if (msgArray.length === 100) { + console.log('The length is 100.'); +} +</pre> + +<h3 id="Example_Creating_a_two-dimensional_array" name="Example:_Creating_a_two-dimensional_array">建立二維陣列</h3> + +<p>以下範例會用字串產生一張西洋棋盤的二維陣列。第一步是將士兵 'p' 從 (6,4) 移動至 (4,4),然後清空原本的位置 (6,4)。</p> + +<pre class="brush: js">var board = [ + ['R','N','B','Q','K','B','N','R'], + ['P','P','P','P','P','P','P','P'], + [' ',' ',' ',' ',' ',' ',' ',' '], + [' ',' ',' ',' ',' ',' ',' ',' '], + [' ',' ',' ',' ',' ',' ',' ',' '], + [' ',' ',' ',' ',' ',' ',' ',' '], + ['p','p','p','p','p','p','p','p'], + ['r','n','b','q','k','b','n','r'] ]; + +console.log(board.join('\n') + '\n\n'); + +// 將士兵往前移兩步 +board[4][4] = board[6][4]; +board[6][4] = ' '; +console.log(board.join('\n')); +</pre> + +<p>以下是輸出結果:</p> + +<pre class="eval">R,N,B,Q,K,B,N,R +P,P,P,P,P,P,P,P + , , , , , , , + , , , , , , , + , , , , , , , + , , , , , , , +p,p,p,p,p,p,p,p +r,n,b,q,k,b,n,r + +R,N,B,Q,K,B,N,R +P,P,P,P,P,P,P,P + , , , , , , , + , , , , , , , + , , , ,p, , , + , , , , , , , +p,p,p,p, ,p,p,p +r,n,b,q,k,b,n,r +</pre> + +<h3 id="使用陣列來以表格顯示多個數值">使用陣列來以表格顯示多個數值</h3> + +<pre class="brush: js">values = []; +for (var x = 0; x < 10; x++){ + values.push([ + 2 ** x, + 2 * x ** 2 + ]) +}; +console.table(values)</pre> + +<p>結果會是</p> + +<pre class="eval">0 1 0 +1 2 2 +2 4 8 +3 8 18 +4 16 32 +5 32 50 +6 64 72 +7 128 98 +8 256 128 +9 512 162</pre> + +<p>(第一欄為索引)</p> + +<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-15.4', 'Array')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>加入新方法:{{jsxref("Array.isArray")}}, {{jsxref("Array.prototype.indexOf", "indexOf")}}, {{jsxref("Array.prototype.lastIndexOf", "lastIndexOf")}}, {{jsxref("Array.prototype.every", "every")}}, {{jsxref("Array.prototype.some", "some")}}, {{jsxref("Array.prototype.forEach", "forEach")}}, {{jsxref("Array.prototype.map", "map")}}, {{jsxref("Array.prototype.filter", "filter")}}, {{jsxref("Array.prototype.reduce", "reduce")}}, {{jsxref("Array.prototype.reduceRight", "reduceRight")}}</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array-objects', 'Array')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>加入新方法:{{jsxref("Array.from")}}, {{jsxref("Array.of")}}, {{jsxref("Array.prototype.find", "find")}}, {{jsxref("Array.prototype.findIndex", "findIndex")}}, {{jsxref("Array.prototype.fill", "fill")}}, {{jsxref("Array.prototype.copyWithin", "copyWithin")}}</td> + </tr> + <tr> + <td>{{SpecName('ES7', '#sec-array-objects', 'Array')}}</td> + <td>{{Spec2('ES7')}}</td> + <td>加入新方法:{{jsxref("Array.prototype.includes()")}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">瀏覽器相容性</h2> + + + +<p>{{Compat("javascript.builtins.Array")}}</p> + +<h2 id="See_also" name="See_also">參見</h2> + +<ul> + <li><a href="/zh-TW/docs/Web/JavaScript/Guide/Working_with_Objects#Indexing_object_properties">JavaScript Guide: “Indexing object properties”</a></li> + <li><a href="/zh-TW/docs/Web/JavaScript/Guide/Predefined_Core_Objects#Array_Object">JavaScript Guide: “Predefined Core Objects: <code>Array</code> Object”</a></li> + <li><a href="/zh-TW/docs/Web/JavaScript/Reference/Operators/Array_comprehensions">Array comprehensions</a></li> + <li><a href="https://github.com/plusdude/array-generics">Polyfill for JavaScript 1.8.5 Array Generics and ECMAScript 5 Array Extras</a></li> + <li><a href="/zh-TW/docs/JavaScript_typed_arrays">Typed Arrays</a></li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/indexof/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/indexof/index.html new file mode 100644 index 0000000000..ff6bbdba76 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/indexof/index.html @@ -0,0 +1,260 @@ +--- +title: Array.prototype.indexOf() +slug: Web/JavaScript/Reference/Global_Objects/Array/indexOf +tags: + - Array + - JavaScript + - Method + - Prototype + - Reference + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/indexOf +--- +<div>{{JSRef}}</div> + +<p><code><strong>indexOf()</strong></code> 方法會回傳給定元素於陣列中第一個被找到之索引,若不存在於陣列中則回傳 -1。</p> + +<div class="note"> +<p><strong>備註:</strong>若是調用字串的方法,請參閱 {{jsxref("String.prototype.indexOf()")}}。</p> +</div> + +<div>{{EmbedInteractiveExample("pages/js/array-indexof.html")}}</div> + + + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox"><var>arr</var>.indexOf(<var>searchElement[</var>, <var>fromIndex]</var>)</pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>searchElement</code></dt> + <dd>欲在陣列中搜尋的元素。</dd> + <dt><code>fromIndex</code> {{optional_inline}}</dt> + <dd>陣列中搜尋的起始索引。若這個索引值大於或等於陣列長度,會直接回傳 -1,意即不會在陣列中搜尋。如果索引值是一個負數,會從陣列的最後一個往回算,最後一個的索引值為 -1,以此類推。注意:儘管往回算,但依然會從左往右全部搜尋。如果負數索引值在回頭計算之後仍然小於 0,則會從左往右全部搜尋。 這個參數的預設值為 0(即搜尋整個陣列)。</dd> +</dl> + +<h3 id="回傳值">回傳值</h3> + +<p>在陣列中找到的第一個元素索引值;沒找到則為 <strong>-1</strong>。</p> + +<h2 id="說明">說明</h2> + +<p><code>indexOf()</code> 用<a href="/zh-TW/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Using_the_Equality_Operators">嚴格相等(strict equality,<code>===</code>)</a>的方式比較陣列中的元素與 <code>searchElement</code> 是否相等。</p> + +<h2 id="範例">範例</h2> + +<h3 id="使用_indexOf()">使用 <code>indexOf()</code></h3> + +<p>下面範例使用<code>indexOf()</code>來定位在陣列中的值。</p> + +<pre class="brush: js">var array = [2, 9, 9]; +array.indexOf(2); // 0 +array.indexOf(7); // -1 +array.indexOf(9, 2); // 2 +array.indexOf(2, -1); // -1 +array.indexOf(2, -3); // 0 +</pre> + +<h3 id="尋找該元素所有出現在陣列中的位置">尋找該元素所有出現在陣列中的位置</h3> + +<pre class="brush: js">var indices = []; +var array = ['a', 'b', 'a', 'c', 'a', 'd']; +var element = 'a'; +var idx = array.indexOf(element); +while (idx != -1) { + indices.push(idx); + idx = array.indexOf(element, idx + 1); +} +console.log(indices); +// [0, 2, 4] +</pre> + +<h3 id="尋找元素是否存在於陣列中,若沒有則加入到陣列裡。">尋找元素是否存在於陣列中,若沒有則加入到陣列裡。</h3> + +<pre class="brush: js">function updateVegetablesCollection (veggies, veggie) { + if (veggies.indexOf(veggie) === -1) { + veggies.push(veggie); + console.log('New veggies collection is : ' + veggies); + } else if (veggies.indexOf(veggie) > -1) { + console.log(veggie + ' already exists in the veggies collection.'); + } +} + +var veggies = ['potato', 'tomato', 'chillies', 'green-pepper']; + +updateVegetablesCollection(veggies, 'spinach'); +// New veggies collection is : potato,tomato,chillies,green-pepper,spinach +updateVegetablesCollection(veggies, 'spinach'); +// spinach already exists in the veggies collection. +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p><code>indexOf()</code> was added to the ECMA-262 standard in the 5th edition; as such it may not be present in all browsers. You can work around this by utilizing the following code at the beginning of your scripts. This will allow you to use <code>indexOf()</code> when there is still no native support. This algorithm matches the one specified in ECMA-262, 5th edition, assuming {{jsxref("Global_Objects/TypeError", "TypeError")}} and {{jsxref("Math.abs()")}} have their original values.</p> + +<p> </p> + +<pre class="brush: js">if (!Array.prototype.indexOf) { + Array.prototype.indexOf = function indexOf(member, startFrom) { + /* + In non-strict mode, if the `this` variable is null or undefined, then it is + set to the window object. Otherwise, `this` is automatically converted to an + object. In strict mode, if the `this` variable is null or undefined, a + `TypeError` is thrown. + */ + if (this == null) { + throw new TypeError("Array.prototype.indexOf() - can't convert `" + this + "` to object"); + } + + var + index = isFinite(startFrom) ? Math.floor(startFrom) : 0, + that = this instanceof Object ? this : new Object(this), + length = isFinite(that.length) ? Math.floor(that.length) : 0; + + if (index >= length) { + return -1; + } + + if (index < 0) { + index = Math.max(length + index, 0); + } + + if (member === undefined) { + /* + Since `member` is undefined, keys that don't exist will have the same + value as `member`, and thus do need to be checked. + */ + do { + if (index in that && that[index] === undefined) { + return index; + } + } while (++index < length); + } else { + do { + if (that[index] === member) { + return index; + } + } while (++index < length); + } + + return -1; + }; +}</pre> + +<p> </p> + +<p>However, if you are more interested in all the little technical bits defined by the ECMA standard, and are less concerned about performance or conciseness, then you may find this more descriptive polyfill to be more usefull.</p> + +<pre class="brush: js">// Production steps of ECMA-262, Edition 5, 15.4.4.14 +// Reference: http://es5.github.io/#x15.4.4.14 +if (!Array.prototype.indexOf) { + Array.prototype.indexOf = function(searchElement, fromIndex) { + + var k; + + // 1. Let o be the result of calling ToObject passing + // the this value as the argument. + if (this == null) { + throw new TypeError('"this" is null or not defined'); + } + + var o = Object(this); + + // 2. Let lenValue be the result of calling the Get + // internal method of o with the argument "length". + // 3. Let len be ToUint32(lenValue). + var len = o.length >>> 0; + + // 4. If len is 0, return -1. + if (len === 0) { + return -1; + } + + // 5. If argument fromIndex was passed let n be + // ToInteger(fromIndex); else let n be 0. + var n = fromIndex | 0; + + // 6. If n >= len, return -1. + if (n >= len) { + return -1; + } + + // 7. If n >= 0, then Let k be n. + // 8. Else, n<0, Let k be len - abs(n). + // If k is less than 0, then let k be 0. + k = Math.max(n >= 0 ? n : len - Math.abs(n), 0); + + // 9. Repeat, while k < len + while (k < len) { + // a. Let Pk be ToString(k). + // This is implicit for LHS operands of the in operator + // b. Let kPresent be the result of calling the + // HasProperty internal method of o with argument Pk. + // This step can be combined with c + // c. If kPresent is true, then + // i. Let elementK be the result of calling the Get + // internal method of o with the argument ToString(k). + // ii. Let same be the result of applying the + // Strict Equality Comparison Algorithm to + // searchElement and elementK. + // iii. If same is true, return k. + if (k in o && o[k] === searchElement) { + return k; + } + k++; + } + return -1; + }; +} +</pre> + +<h2 id="規範">規範</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.14', 'Array.prototype.indexOf')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.6.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.indexof', 'Array.prototype.indexOf')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.indexof', 'Array.prototype.indexOf')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.indexOf")}}</p> +</div> + +<h2 id="相容性備註">相容性備註</h2> + +<ul> + <li>Starting with Firefox 47 {{geckoRelease(47)}}, this method will no longer return <code>-0</code>. For example, <code>[0].indexOf(0, -0)</code> will now always return <code>+0</code> ({{bug(1242043)}}).</li> +</ul> + +<h2 id="參見">參見</h2> + +<ul> + <li>{{jsxref("Array.prototype.lastIndexOf()")}}</li> + <li>{{jsxref("TypedArray.prototype.indexOf()")}}</li> + <li>{{jsxref("String.prototype.indexOf()")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/isarray/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/isarray/index.html new file mode 100644 index 0000000000..f610cd1f54 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/isarray/index.html @@ -0,0 +1,134 @@ +--- +title: Array.isArray() +slug: Web/JavaScript/Reference/Global_Objects/Array/isArray +tags: + - Array + - ECMAScript5 + - JavaScript + - Method + - Reference + - polyfill + - 方法 + - 陣列 +translation_of: Web/JavaScript/Reference/Global_Objects/Array/isArray +--- +<div>{{JSRef}}</div> + +<p><code><strong>Array.isArray()</strong></code> 函式會檢查傳入的值是否為一個 {{jsxref("Array")}}。</p> + +<pre class="brush: js">Array.isArray([1, 2, 3]); // true +Array.isArray({foo: 123}); // false +Array.isArray('foobar'); // false +Array.isArray(undefined); // false +</pre> + +<h2 id="Syntax" name="Syntax">語法</h2> + +<pre class="syntaxbox">Array.isArray(<var>obj</var>)</pre> + +<h3 id="Parameters" name="Parameters">參數</h3> + +<dl> + <dt><code>obj</code></dt> + <dd>要檢查的物件。</dd> +</dl> + +<h3 id="回傳值">回傳值</h3> + +<p>若物件為 {{jsxref("Array")}} 回傳 <code>true</code>;否則回傳 <code>false</code>。</p> + +<h2 id="Description" name="Description">描述</h2> + +<p>檢查傳入的物件是否為陣列({{jsxref("Array")}}),如果是便回傳 <code>true</code>,否則回傳 <code>false</code>。</p> + +<p>更多細節請參考 <a href="http://web.mit.edu/jwalden/www/isArray.html">“Determining with absolute accuracy whether or not a JavaScript object is an array”</a>。</p> + +<h2 id="Examples" name="Examples">範例</h2> + +<pre class="brush: js">// 下方都回傳 true +Array.isArray([]); +Array.isArray([1]); +Array.isArray(new Array()); +Array.isArray(new Array('a', 'b', 'c', 'd')); +Array.isArray(new Array(3)); +// 小細節:Array.prototype 本身是陣列: +Array.isArray(Array.prototype); + +// 下方都回傳 false +Array.isArray(); +Array.isArray({}); +Array.isArray(null); +Array.isArray(undefined); +Array.isArray(17); +Array.isArray('Array'); +Array.isArray(true); +Array.isArray(false); +Array.isArray({ __proto__: Array.prototype }); +</pre> + +<h3 id="instanceof_vs_isArray"><code>instanceof</code> vs <code>isArray</code></h3> + +<p>當檢查 <code>Array</code> 實例時,<code>Array.isArray</code> 相較於 <code>instanceof</code> 更加推薦,因為它可以穿透 <code>iframes</code>。</p> + +<pre class="brush: js">var iframe = document.createElement('iframe'); +document.body.appendChild(iframe); +xArray = window.frames[window.frames.length-1].Array; +var arr = new xArray(1,2,3); // [1,2,3] + +// 正確地檢查陣列型態 +Array.isArray(arr); // true +// 有害地,因為它不能在 iframes 之間正常運作 +arr instanceof Array; // false +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p>如果 <code>Array.isArray()</code> 不存在於您的環境,在其他程式碼前執行下列程式碼可建置 <code>Array.isArray()</code>。</p> + +<pre class="brush: js">if (!Array.isArray) { + Array.isArray = function(arg) { + return Object.prototype.toString.call(arg) === '[object Array]'; + }; +} +</pre> + +<h2 id="Specifications" name="Specifications">規範</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.3.2', 'Array.isArray')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.8.5.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.isarray', 'Array.isArray')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.isarray', 'Array.isArray')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">瀏覽器相容性</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.isArray")}}</p> +</div> + +<h2 id="See_also" name="See_also">參見</h2> + +<ul> + <li>{{jsxref("Array")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/join/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/join/index.html new file mode 100644 index 0000000000..0beaecebdd --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/join/index.html @@ -0,0 +1,109 @@ +--- +title: Array.prototype.join() +slug: Web/JavaScript/Reference/Global_Objects/Array/join +tags: + - Array + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/join +--- +<div>{{JSRef}}</div> + +<p><code><strong>join()</strong></code> 方法會將陣列(或一個<a href="/zh-TW/docs/Web/JavaScript/Guide/Indexed_collections#Working_with_array-like_objects">類陣列(array-like)物件</a>)中所有的元素連接、合併成一個字串,並回傳此字串。</p> + +<div>{{EmbedInteractiveExample("pages/js/array-join.html")}}</div> + + + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox"><var>arr</var>.join(<em>[</em><var>separator]</var>)</pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>separator</code> {{optional_inline}}</dt> + <dd>用來隔開陣列中每個元素的字串。如果必要的話,separator 會自動被轉成字串型態。如果未傳入此參數,陣列中的元素將預設用英文逗號(「,」)隔開。如果 <code>separator</code> 是空字串,合併後,元素間不會有任何字元。</dd> +</dl> + +<h3 id="回傳值">回傳值</h3> + +<p>一個合併所有陣列元素的字串。假如 <code><em>arr</em>.length</code> 為 <code>0</code>,將回傳空字串。</p> + +<h2 id="描述">描述</h2> + +<p>將所有陣列中的元素轉成字串型態後,連接合併成一個字串。任何 <code>undefined</code> 或 <code>null</code> 的元素都會被視為空字串處理。</p> + +<h2 id="範例">範例</h2> + +<h3 id="舉例四種合併用法">舉例四種合併用法</h3> + +<p>下方的範例中,首先宣告一個陣列—<code>a</code>,其中有三個元素。接著分別用:預設值、逗號、加號和空字串將陣列連接。</p> + +<pre class="brush: js">var a = ['Wind', 'Rain', 'Fire']; +a.join(); // 'Wind,Rain,Fire' +a.join(', '); // 'Wind, Rain, Fire' +a.join(' + '); // 'Wind + Rain + Fire' +a.join(''); // 'WindRainFire'</pre> + +<h3 id="合併一個類陣列(array-like)物件">合併一個類陣列(array-like)物件</h3> + +<p>下方的範例將合併一個類陣列(array-like)物件(<code><a href="/zh-TW/docs/Web/JavaScript/Reference/Functions/arguments">arguments</a></code>),藉由 {{jsxref("Function.prototype.call")}} 來呼叫 <code>Array.prototype.join</code>。</p> + +<pre class="brush: js">function f(a, b, c) { + var s = Array.prototype.join.call(arguments); + console.log(s); // '<span class="message-body-wrapper"><span class="message-flex-body"><span class="devtools-monospace message-body"><span class="objectBox objectBox-string">1,a,true'</span></span></span></span> +} +f(1, 'a', true); +//expected output: "1,a,true" +</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('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.1.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.5', 'Array.prototype.join')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.join', 'Array.prototype.join')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.join', 'Array.prototype.join')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.join")}}</p> +</div> + +<h2 id="參見">參見</h2> + +<ul> + <li>{{jsxref("String.prototype.split()")}}</li> + <li>{{jsxref("Array.prototype.toString()")}}</li> + <li>{{jsxref("TypedArray.prototype.join()")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/keys/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/keys/index.html new file mode 100644 index 0000000000..fa71299ecb --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/keys/index.html @@ -0,0 +1,76 @@ +--- +title: Array.prototype.keys() +slug: Web/JavaScript/Reference/Global_Objects/Array/keys +tags: + - Array + - ECMAScript 2015 + - Iterator + - JavaScript + - Method + - Prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Array/keys +--- +<div>{{JSRef}}</div> + +<p><code><strong>keys()</strong></code> 方法會回傳一個包含陣列中的每一個索引之鍵(keys)的新 <code><strong>Array Iterator</strong></code> 物件。</p> + +<div>{{EmbedInteractiveExample("pages/js/array-keys.html")}}</div> + + + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox"><var>arr</var>.keys()</pre> + +<h3 id="回傳值">回傳值</h3> + +<p>一個新的 {{jsxref("Array")}} 迭代器(iterator)物件。</p> + +<h2 id="範例">範例</h2> + +<h3 id="鍵迭代器不會乎略陣列中的空元素">鍵迭代器不會乎略陣列中的空元素</h3> + +<pre class="brush: js">var arr = ['a', , 'c']; +var sparseKeys = Object.keys(arr); +var denseKeys = [...arr.keys()]; +console.log(sparseKeys); // ['0', '2'] +console.log(denseKeys); // [0, 1, 2] +</pre> + +<h2 id="規範">規範</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-array.prototype.keys', 'Array.prototype.keys')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.keys', 'Array.prototype.keys')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.keys")}}</p> +</div> + +<h2 id="參見">參見</h2> + +<ul> + <li>{{jsxref("Array.prototype.values()")}}</li> + <li>{{jsxref("Array.prototype.entries()")}}</li> + <li><a href="/zh-TW/docs/Web/JavaScript/Reference/Iteration_protocols">迭代協議</a></li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/lastindexof/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/lastindexof/index.html new file mode 100644 index 0000000000..930b45d3e3 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/lastindexof/index.html @@ -0,0 +1,168 @@ +--- +title: Array.prototype.lastIndexOf() +slug: Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf +tags: + - Array + - ECMAScript 5 + - JavaScript + - Method + - Prototype + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf +--- +<div>{{JSRef}}</div> + +<p><code><strong>lastIndexOf()</strong></code> 方法會回傳給定元素於陣列中最後一個被找到之索引,若不存在於陣列中則回傳 -1。搜尋的方向為由陣列尾部向後(即向前)尋找,啟始於 <code>fromIndex</code>。</p> + +<div>{{EmbedInteractiveExample("pages/js/array-lastindexof.html")}}</div> + + + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox"><var>arr</var>.lastIndexOf(<var>searchElement</var>) +<var>arr</var>.lastIndexOf(<var>searchElement</var>, <var>fromIndex</var>) +</pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>searchElement</code></dt> + <dd>欲在陣列中搜尋的元素。</dd> + <dt><code>fromIndex</code> {{optional_inline}}</dt> + <dd>要由陣列尾部向後(即向前)搜尋的啟始索引。預設為陣列長度減一(<code>arr.length - 1</code>),即會搜尋整個陣列。假如索引大於等於陣列長度,會搜尋整個陣列。如果索引值為負數,會從陣列的最後一個往回算,最後一個的索引值為 -1,以此類推。注意:儘管往回算,但依然會從右往左全部搜尋。如果負數索引值在回頭計算之後仍然小於 0,將會回傳 -1,即不會搜尋陣列。</dd> +</dl> + +<h3 id="回傳值">回傳值</h3> + +<p>在陣列中找到的最後一個元素索引值;沒找到則為 <strong>-1</strong>。</p> + +<h2 id="描述">描述</h2> + +<p><code>lastIndexOf</code> compares <code>searchElement</code> to elements of the Array using <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Using_the_Equality_Operators">strict equality</a> (the same method used by the ===, or triple-equals, operator).</p> + +<h2 id="範例">範例</h2> + +<h3 id="使用_lastIndexOf">使用 <code>lastIndexOf</code></h3> + +<p>The following example uses <code>lastIndexOf</code> to locate values in an array.</p> + +<pre class="brush: js">var numbers = [2, 5, 9, 2]; +numbers.lastIndexOf(2); // 3 +numbers.lastIndexOf(7); // -1 +numbers.lastIndexOf(2, 3); // 3 +numbers.lastIndexOf(2, 2); // 0 +numbers.lastIndexOf(2, -2); // 0 +numbers.lastIndexOf(2, -1); // 3 +</pre> + +<h3 id="尋找該元素所有出現在陣列中的位置">尋找該元素所有出現在陣列中的位置</h3> + +<p>The following example uses <code>lastIndexOf</code> to find all the indices of an element in a given array, using {{jsxref("Array.prototype.push", "push")}} to add them to another array as they are found.</p> + +<pre class="brush: js">var indices = []; +var array = ['a', 'b', 'a', 'c', 'a', 'd']; +var element = 'a'; +var idx = array.lastIndexOf(element); +while (idx != -1) { + indices.push(idx); + idx = (idx > 0 ? array.lastIndexOf(element, idx - 1) : -1); +} + +console.log(indices); +// [4, 2, 0] +</pre> + +<p>Note that we have to handle the case <code>idx == 0</code> separately here because the element will always be found regardless of the <code>fromIndex</code> parameter if it is the first element of the array. This is different from the {{jsxref("Array.prototype.indexOf", "indexOf")}} method.</p> + +<h2 id="Polyfill">Polyfill</h2> + +<p><code>lastIndexOf</code> was added to the ECMA-262 standard in the 5th edition; as such it may not be present in other implementations of the standard. You can work around this by inserting the following code at the beginning of your scripts, allowing use of <code>lastIndexOf</code> in implementations which do not natively support it. This algorithm is exactly the one specified in ECMA-262, 5th edition, assuming {{jsxref("Object")}}, {{jsxref("TypeError")}}, {{jsxref("Number")}}, {{jsxref("Math.floor")}}, {{jsxref("Math.abs")}}, and {{jsxref("Math.min")}} have their original values.</p> + +<pre class="brush: js">// Production steps of ECMA-262, Edition 5, 15.4.4.15 +// Reference: http://es5.github.io/#x15.4.4.15 +if (!Array.prototype.lastIndexOf) { + Array.prototype.lastIndexOf = function(searchElement /*, fromIndex*/) { + 'use strict'; + + if (this === void 0 || this === null) { + throw new TypeError(); + } + + var n, k, + t = Object(this), + len = t.length >>> 0; + if (len === 0) { + return -1; + } + + n = len - 1; + if (arguments.length > 1) { + n = Number(arguments[1]); + if (n != n) { + n = 0; + } + else if (n != 0 && n != (1 / 0) && n != -(1 / 0)) { + n = (n > 0 || -1) * Math.floor(Math.abs(n)); + } + } + + for (k = n >= 0 ? Math.min(n, len - 1) : len - Math.abs(n); k >= 0; k--) { + if (k in t && t[k] === searchElement) { + return k; + } + } + return -1; + }; +} +</pre> + +<p>Again, note that this implementation aims for absolute compatibility with <code>lastIndexOf</code> in Firefox and the SpiderMonkey JavaScript engine, including in several cases which are arguably edge cases. If you intend to use this in real-world applications, you may be able to calculate <code>from</code> with less complicated code if you ignore those cases.</p> + +<h2 id="規範">規範</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.15', 'Array.prototype.lastIndexOf')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.6.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.lastindexof', 'Array.prototype.lastIndexOf')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.lastindexof', 'Array.prototype.lastIndexOf')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.lastIndexOf")}}</p> +</div> + +<h2 id="相容性備註">相容性備註</h2> + +<ul> + <li>Starting with Firefox 47 {{geckoRelease(47)}}, this method will no longer return <code>-0</code>. For example, <code>[0].lastIndexOf(0, -0)</code> will now always return <code>+0</code> ({{bug(1242043)}}).</li> +</ul> + +<h2 id="參見">參見</h2> + +<ul> + <li>{{jsxref("Array.prototype.indexOf()")}}</li> + <li>{{jsxref("TypedArray.prototype.lastIndexOf()")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/length/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/length/index.html new file mode 100644 index 0000000000..453564d528 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/length/index.html @@ -0,0 +1,131 @@ +--- +title: Array.length +slug: Web/JavaScript/Reference/Global_Objects/Array/length +translation_of: Web/JavaScript/Reference/Global_Objects/Array/length +--- +<div>{{JSRef}}</div> + +<p><code><strong>length</strong></code> 為<code>Array物件的屬性</code> ,可供設定或回傳該陣列實體中包含的元素個數。其值必為一大於零、32位元、且恆大於該陣列最大索引數的正整數。</p> + +<pre class="brush: js notranslate">var items = ['shoes', 'shirts', 'socks', 'sweaters']; +items.length; + +// returns 4</pre> + +<h2 id="描述">描述</h2> + +<p><code>length</code> 屬性的值必為一正整數,其值必介於 0 ~ 2<sup>32</sup> (不包含)之間.</p> + +<pre class="brush: js notranslate">var namelistA = new Array(4294967296); //2<sup>32</sup><sup> = </sup>4294967296 +var namelistC = new Array(-100) //負數 + +console.log(namelistA.length); //RangeError: Invalid array length +console.log(namelistC.length); //RangeError: Invalid array length + + + +var namelistB = []; +namelistB.length = Math.pow(2,32)-1; //將長度設定介於 0 ~ 2<sup>32 </sup>-1 +console.log(namelistB.length); + +//4294967295</pre> + +<p>你可以透過改變 <code>length</code> 屬性來改變陣列的長度。當你透過 <code>length</code> 屬性來增加陣列的長度時,陣列中實際的元素也會隨之增加。舉例來說,當你將 array.length 由 2 增加為3,則改動後該陣列即擁有3個元素,該新增的元素則會是一個不可迭代(non-iterable)的空槽(empty slot)。</p> + +<pre class="notranslate">const arr = [1, 2]; +console.log(arr); +// [ 1, 2 ] + +arr.length = 5; // 將arr的length由2改成5 +console.log(arr); +// [ 1, 2, <3 empty items> ] + +arr.forEach(element => console.log(element)); // 空元素無法被迭代 +// 1 +// 2</pre> + +<p>如上所見,<code>length</code> 屬性不盡然代表陣列中所有已定義的元素個數。詳見 <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#Relationship_between_length_and_numerical_properties" title="Relationship between length and numerical properties">length 與數值屬性的關係</a>。</p> + +<p>{{js_property_attributes(1, 0, 0)}}</p> + +<div> +<ul> + <li><code>Writable</code>: 如果此屬性值為<code>false</code>,則該屬性的內容值無法被改動。</li> + <li><code>Configurable</code>: 如果此屬性值為<code>false</code>,任何刪除屬性或更改其屬性的操作(<code>Writable</code>, <code>Configurable</code>, or <code>Enumerable</code>)皆會失敗。</li> + <li><code>Enumerable</code>: 如果此屬性值為<code>true</code>,該內容值可倍 <a href="/en-US/docs/Web/JavaScript/Reference/Statements/for">for</a> 或 <a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...in">for..in</a> 迴圈迭代處理。</li> +</ul> +</div> + +<h2 id="範例">範例</h2> + +<h3 id="對陣列進行迭代處理">對陣列進行迭代處理</h3> + +<p>以下範例中, 陣列 <code>numbers</code> 透過 <code>length</code> 屬性進行迭代操作,並將其內容值加倍。</p> + +<pre class="brush: js notranslate">var numbers = [1, 2, 3, 4, 5]; +var length = numbers.length; +for (var i = 0; i < length; i++) { + numbers[i] *= 2; +} +// numbers 內容值變為 [2, 4, 6, 8, 10] +</pre> + +<h3 id="縮減陣列">縮減陣列</h3> + +<p>以下範例中, 陣列 <code>numbers</code> 的長度若大於 3,則將其長度縮減至 3。</p> + +<pre class="brush: js notranslate">var numbers = [1, 2, 3, 4, 5]; + +if (numbers.length > 3) { + numbers.length = 3; +} + +console.log(numbers); // [1, 2, 3] +console.log(numbers.length); // 3 +</pre> + +<h2 id="規格">規格</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.5.2', 'Array.length')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-properties-of-array-instances-length', 'Array.length')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-properties-of-array-instances-length', 'Array.length')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.length")}}</p> +</div> + +<h2 id="其他">其他</h2> + +<ul> + <li>{{jsxref("Array")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/map/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/map/index.html new file mode 100644 index 0000000000..d1838ce6ae --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/map/index.html @@ -0,0 +1,320 @@ +--- +title: Array.prototype.map() +slug: Web/JavaScript/Reference/Global_Objects/Array/map +tags: + - Array + - ECMAScript 5 + - ECMAScript6 + - JavaScript + - Method + - Prototype + - Reference + - polyfill + - 陣列 +translation_of: Web/JavaScript/Reference/Global_Objects/Array/map +--- +<div>{{JSRef}}</div> + +<p><span class="seoSummary"><code><strong>map()</strong></code> 方法會建立一個新的陣列,其內容為原陣列的每一個元素經由回呼函式運算後所回傳的結果之集合。</span></p> + +<div>{{EmbedInteractiveExample("pages/js/array-map.html")}}</div> + + + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox">let <var>new_array</var> = <var>arr</var>.map(function <var>callback</var>( <var>currentValue</var>[, <var>index</var>[, <var>array</var>]]) { + // return element for new_array +}[, <var>thisArg</var>]) +</pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>callback</code></dt> + <dd> + <p>呼叫 <code><var>arr</var></code> 所有元素的回呼函式。新數值會在每次執行 <code><var>callback</var></code> 時加到 <code><var>new_array</var></code>。</p> + + <p><code><var>callback</var></code> 函式可傳入以下三個參數:</p> + + <dl> + <dt></dt> + <dt><code>currentValue</code></dt> + <dd>原陣列目前所迭代處理中的元素。</dd> + <dt><code>index</code>{{optional_inline}}</dt> + <dd>原陣列目前所迭代處理中的元素之索引。</dd> + <dt><code>array</code>{{optional_inline}}</dt> + <dd>呼叫 <code>map</code> 方法的陣列。</dd> + </dl> + </dd> + <dt><code>thisArg</code>{{optional_inline}}</dt> + <dd>選擇性的參數。執行 <code>callback</code> 回呼函式的 <code>this</code> 值。</dd> +</dl> + +<h3 id="回傳值">回傳值</h3> + +<p>一個所有元素皆為回呼函式運算結果的新陣列。</p> + +<h2 id="描述">描述</h2> + +<p><code>map</code> 會將所有陣列中的元素依序<strong>分別傳入一次</strong>至 <code><var>callback</var></code> 函式當中,並以此回呼函式每一次被呼叫的回傳值來建構一個新的陣列。<code>callback</code> 函式只會於陣列目前迭代之索引有指派值時(包含{{jsxref("undefined")}})被調用,而在該陣列索引沒有元素時(即未被設定的索引:已被刪除或從未被賦值)並不會呼叫回呼函式。</p> + +<p>它<em>並不能</em>呼叫以下元素:</p> + +<ul> + <li>不存在的索引、</li> + <li>沒被刪除、</li> + <li>沒被賦值。</li> +</ul> + +<h3 id="什麼時候不要用_map">什麼時候<em>不要用</em> map()</h3> + +<p>因為 <code>map</code> 會建立新的陣列,如果在不想建立新陣列時使用該方法,就會變成反模式(anti-pattern):這種情況下,要使用 <a href="/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach"><code>forEach</code></a> 或 <a href="/zh-TW/docs/Web/JavaScript/Reference/Statements/for...of"><code>for-of</code></a>。</p> + +<p>以下情況不應該使用 <code>map</code>;</p> + +<ol> + <li>不使用回傳的新陣列,</li> + <li>或/且不需要回傳新陣列。</li> +</ol> + +<p><code>callback</code> 函式於被調用時會傳入三個參數:元素值、元素之索引、以及被迭代的陣列物件。</p> + +<p>若有提供 <code>thisArg</code> 參數予 <code>map</code> 方法,<code>thisArg</code> 將會被當作回呼函式的 <code>this</code> 值,否則 <code>this</code> 會是 {{jsxref("undefined")}}。<code>callback</code> 的最終 <code>this</code> 值是依據<a href="/zh-TW/docs/Web/JavaScript/Reference/Operators/this">函式的 <code>this</code> 規則</a>來決定。</p> + +<p><code>map</code> 不會修改呼叫它的原始陣列(雖然在 <code>callback</code> 執行時有可能會這麼做)。</p> + +<p>由 <code>map</code> 方法所回傳之新陣列的範圍,於 <code>callback</code> 函式第一次被調用之前就已經被設定。而在呼叫 <code>map</code> 之後才加至原始陣列中的元素,將不會傳入 <code>callback</code> 當中。假如原始陣列中元素的值改變了,則 <code>callback</code> 得到此元素的值將會是 <code>map</code> 傳入元素當下的值。而在呼叫 <code>map</code> 之後、且於被 <code>map</code> 傳入 <code>callback</code> 之前就被刪除的原始陣列元素,並不會被 <code>map</code> 迭代到。<br> + <br> + 依據規範中定義的演算法,若呼叫 <code>map</code> 方法的原始陣列為一稀疏(sparse)陣列,則回傳的新陣列也會是在同樣索引中留空的稀疏陣列。</p> + +<h2 id="範例">範例</h2> + +<h3 id="把一個數字陣列轉換成對應的開根號後的數字陣列">把一個數字陣列轉換成對應的開根號後的數字陣列</h3> + +<p>以下的程式碼把一個數字陣列(array of numbers) 轉換成一個 <strong>新的</strong>以該數字陣列裡的一個個數做開根號計算的數字陣列.</p> + +<pre class="brush: js">var numbers = [1, 4, 9]; +var roots = numbers.map(Math.sqrt); //map會return一個新的array +// roots 現在是 [1, 2, 3] +/* numbers 還是 [1, 4, 9],這證明了 map() 不會去變動到 numbers 的值, + map 內部是做了 immutable 的機制,Array.prototype 底下的這些高階函式 + 大多都具有這樣函數式編程裡非常注重的特性 - immutable,不會去改變資料 + 來源本身原有的值 +*/ </pre> + +<h3 id="使用_map_將陣列中的物件變更格式">使用 map 將陣列中的物件變更格式</h3> + +<p>以下程式碼取出一陣列,將其中物件變更格式後建立為一個新的陣列並傳回。</p> + +<pre class="brush: js">var kvArray = [{key: 1, value: 10}, + {key: 2, value: 20}, + {key: 3, value: 30}]; + +var reformattedArray = kvArray.map(function(obj) { + var rObj = {}; + rObj[obj.key] = obj.value; + return rObj; +}); + +// reformattedArray 現在是 [{1: 10}, {2: 20}, {3: 30}], + +// kvArray 仍然是: +// [{key: 1, value: 10}, +// {key: 2, value: 20}, +// {key: 3, value: 30}] +</pre> + +<h3 id="使用帶參數的函式將一數字陣列進行對應">使用帶參數的函式將一數字陣列進行對應</h3> + +<p>以下程式碼示範如何使用帶有一個參數的函式來操作 map。這個參數會自動地逐一取出原始陣列中各個元素來使用。</p> + +<pre class="brush: js">var numbers = [1, 4, 9]; +var doubles = numbers.map(function(num) { + return num * 2; +}); + +// doubles 現在是 [2, 8, 18] +// numbers 仍然是 [1, 4, 9] +</pre> + +<h3 id="使用_map_於泛型陣列">使用 <code>map</code> 於泛型陣列</h3> + +<p>以下範例示範如何將一個 {{jsxref("String")}} 陣列轉換為 byte 陣列:</p> + +<pre class="brush: js">var map = Array.prototype.map; +var a = map.call('Hello World', function(x) { + return x.charCodeAt(0); +}); +// a 現在等於 [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100] +</pre> + +<h3 id="使用_map_遍歷_querySelectorAll">使用 <code>map</code> 遍歷 <code>querySelectorAll</code></h3> + +<p>本範例將展示如何遍歷由 <code>querySelectorAll</code> 所產生的物件。我們將得到所有的選項、並印在主控台上:</p> + +<pre class="brush: js">var elems = document.querySelectorAll('select option:checked'); +var values = Array.prototype.map.call(elems, function(obj) { + return obj.value; +}); +</pre> + +<p>如果用上 {{jsxref("Array.from()")}} 方法的話會更簡單。</p> + +<h3 id="棘手的範例">棘手的範例</h3> + +<p><a href="http://www.wirfs-brock.com/allen/posts/166">(透過連結的部落格啟發)</a></p> + +<p>透過一個(被遍歷元素的)參數叫出回調是個常見的用法。有些函式也常常在含有其他可選參數的情況下,使用上一個參數。這種行為常常會給人帶來困惑。</p> + +<pre class="brush: js">// Consider: +['1', '2', '3'].map(parseInt); +// 以為會是 [1, 2, 3] 嗎 +// 其實是 [1, NaN, NaN] + +// parseInt 通常只用上一個參數 argument,但他其實用了兩個: +// 第一個是表達式,第二個則是進位數。 +// 對該回呼函式來說 Array.prototype.map 帶了三個參數: +// 元素、索引、陣列 +// 第三個參數會被 parseInt 忽略,但它可不會忽略第二個, +// 因此可能造成困惑。可以去看上面提到的部落格文章以獲知詳情。 + +function returnInt(element) { + return parseInt(element, 10); +} + +['1', '2', '3'].map(returnInt); // [1, 2, 3] +// Actual result is an array of numbers (as expected) + +// Same as above, but using the concise arrow function syntax +['1', '2', '3'].map( str => parseInt(str) ); + +// A simpler way to achieve the above, while avoiding the "gotcha": +['1', '2', '3'].map(Number); // [1, 2, 3] +// but unlike `parseInt` will also return a float or (resolved) exponential notation: +['1.1', '2.2e2', '3e300'].map(Number); // [1.1, 220, 3e+300] +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p><code>map</code> was added to the ECMA-262 standard in the 5th edition; as such it may not be present in all implementations of the standard. You can work around this by inserting the following code at the beginning of your scripts, allowing use of <code>map</code> in implementations which do not natively support it. This algorithm is exactly the one specified in ECMA-262, 5th edition, assuming {{jsxref("Object")}}, {{jsxref("TypeError")}}, and {{jsxref("Array")}} have their original values and that <code>callback.call</code> evaluates to the original value of <code>{{jsxref("Function.prototype.call")}}</code>.</p> + +<pre class="brush: js">// Production steps of ECMA-262, Edition 5, 15.4.4.19 +// Reference: http://es5.github.io/#x15.4.4.19 +if (!Array.prototype.map) { + + Array.prototype.map = function(callback/*, thisArg*/) { + + var T, A, k; + + if (this == null) { + throw new TypeError('this is null or not defined'); + } + + // 1. Let O be the result of calling ToObject passing the |this| + // value as the argument. + var O = Object(this); + + // 2. Let lenValue be the result of calling the Get internal + // method of O with the argument "length". + // 3. Let len be ToUint32(lenValue). + var len = O.length >>> 0; + + // 4. If IsCallable(callback) is false, throw a TypeError exception. + // See: http://es5.github.com/#x9.11 + if (typeof callback !== 'function') { + throw new TypeError(callback + ' is not a function'); + } + + // 5. If thisArg was supplied, let T be thisArg; else let T be undefined. + if (arguments.length > 1) { + T = arguments[1]; + } + + // 6. Let A be a new array created as if by the expression new Array(len) + // where Array is the standard built-in constructor with that name and + // len is the value of len. + A = new Array(len); + + // 7. Let k be 0 + k = 0; + + // 8. Repeat, while k < len + while (k < len) { + + var kValue, mappedValue; + + // a. Let Pk be ToString(k). + // This is implicit for LHS operands of the in operator + // b. Let kPresent be the result of calling the HasProperty internal + // method of O with argument Pk. + // This step can be combined with c + // c. If kPresent is true, then + if (k in O) { + + // i. Let kValue be the result of calling the Get internal + // method of O with argument Pk. + kValue = O[k]; + + // ii. Let mappedValue be the result of calling the Call internal + // method of callback with T as the this value and argument + // list containing kValue, k, and O. + mappedValue = callback.call(T, kValue, k, O); + + // iii. Call the DefineOwnProperty internal method of A with arguments + // Pk, Property Descriptor + // { Value: mappedValue, + // Writable: true, + // Enumerable: true, + // Configurable: true }, + // and false. + + // In browsers that support Object.defineProperty, use the following: + // Object.defineProperty(A, k, { + // value: mappedValue, + // writable: true, + // enumerable: true, + // configurable: true + // }); + + // For best browser support, use the following: + A[k] = mappedValue; + } + // d. Increase k by 1. + k++; + } + + // 9. return A + return A; + }; +} +</pre> + +<h2 id="規範">規範</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.map', 'Array.prototype.map')}}</td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.map")}}</p> +</div> + +<h2 id="參見">參見</h2> + +<ul> + <li>{{jsxref("Array.prototype.forEach()")}}</li> + <li>{{jsxref("Map")}} object</li> + <li>{{jsxref("Array.from()")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/of/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/of/index.html new file mode 100644 index 0000000000..31118bbeb6 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/of/index.html @@ -0,0 +1,98 @@ +--- +title: Array.of() +slug: Web/JavaScript/Reference/Global_Objects/Array/of +tags: + - Array + - ECMAScript 2015 + - JavaScript + - Method + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/of +--- +<div>{{JSRef}}</div> + +<p><code><strong>Array.of()</strong></code> 方法會由引數(arguments)的數量來建立一個新的 <code>Array</code> 實體,而不管引數的數量或類型為何。</p> + +<p><code><strong>Array.of()</strong></code> 與 <code><strong>Array</strong></code> 建構式之間的不同在於如何處理整數引數:<code><strong>Array.of(7)</strong></code> 會建立一個擁有單個元素—<code>7</code>—的陣列,而 <code><strong>Array(7)</strong></code> 會建立一個 <code>length</code> 屬性值為 7 的空陣列(<strong>註:</strong>這意味著這個陣列有 7 個空缺欄位(empty slots),而非 7 個值為 <code>undefined</code> 的欄位)。</p> + +<pre class="brush: js">Array.of(7); // [7] +Array.of(1, 2, 3); // [1, 2, 3] + +Array(7); // [ , , , , , , ] +Array(1, 2, 3); // [1, 2, 3] +</pre> + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox">Array.of(<var>element0</var>[, <var>element1</var>[, ...[, <var>elementN</var>]]])</pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>element<em>N</em></code></dt> + <dd>要用來成為新建立之陣列的元素。</dd> +</dl> + +<h3 id="回傳值">回傳值</h3> + +<p>一個新的 {{jsxref("Array")}} 實體。</p> + +<h2 id="描述">描述</h2> + +<p>此函式是 ECMAScript 2015 標準的一部分。更多資訊可參考 <a href="https://gist.github.com/rwaldron/1074126"><code>Array.of</code> and <code>Array.from</code> proposal</a> 以及 <a href="https://gist.github.com/rwaldron/3186576"><code>Array.of</code> polyfill</a>。</p> + +<h2 id="範例">範例</h2> + +<pre class="brush: js">Array.of(1); // [1] +Array.of(1, 2, 3); // [1, 2, 3] +Array.of(undefined); // [undefined] +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p>若所有執行環境沒有原生支援,可以在其他程式之前先執行以下程式碼來建立 <code>Array.of()</code>。</p> + +<pre class="brush: js">if (!Array.of) { + Array.of = function() { + return Array.prototype.slice.call(arguments); + }; +} +</pre> + +<h2 id="規範">規範</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-array.of', 'Array.of')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.of', 'Array.of')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.of")}}</p> +</div> + +<h2 id="參見">參見</h2> + +<ul> + <li>{{jsxref("Array")}}</li> + <li>{{jsxref("Array.from()")}}</li> + <li>{{jsxref("TypedArray.of()")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/pop/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/pop/index.html new file mode 100644 index 0000000000..3124fa26bc --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/pop/index.html @@ -0,0 +1,98 @@ +--- +title: Array.prototype.pop() +slug: Web/JavaScript/Reference/Global_Objects/Array/pop +tags: + - Array + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/pop +--- +<div>{{JSRef}}</div> + +<p><code><strong>pop()</strong></code> 方法會移除並回傳陣列的<strong>最後一個</strong>元素。此方法會改變陣列的長度。</p> + +<div>{{EmbedInteractiveExample("pages/js/array-pop.html")}}</div> + + + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox"><var>arr</var>.pop()</pre> + +<h3 id="回傳值">回傳值</h3> + +<p>自陣列中移除的元素;若陣列為空,則為 {{jsxref("undefined")}}。</p> + +<h2 id="描述">描述</h2> + +<p><code>pop</code> 方法會移除陣列中的最後一個元素,並將該值回傳給呼叫者。</p> + +<p><code>pop</code> 方法被刻意設計為具通用性;此方法可以藉由 {{jsxref("Function.call", "called", "", 1)}} 或 {{jsxref("Function.apply", "applied", "", 1)}} 應用於類似陣列的物件上。若欲應用此方法的物件不包含代表一系列啟始為零之數字屬性序列長度的 <code>length</code> 屬性,可能是不具任何意義的行為。</p> + +<p>如果於空陣列呼叫 <code>pop()</code>,將會回傳 {{jsxref("undefined")}}。</p> + +<h2 id="範例">範例</h2> + +<h3 id="移除陣列的最後一個元素">移除陣列的最後一個元素</h3> + +<p>下面的程式碼為一個包含四個元素的 <code>myFish</code> 陣列,接著移除此陣列的最後一個元素。</p> + +<pre class="brush: js">var myFish = ['angel', 'clown', 'mandarin', 'sturgeon']; + +var popped = myFish.pop(); + +console.log(myFish); // ['angel', 'clown', 'mandarin' ] + +console.log(popped); // 'sturgeon'</pre> + +<h2 id="規範">規範</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Initial definition. Implemented in JavaScript 1.2.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.6', 'Array.prototype.pop')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.pop', 'Array.prototype.pop')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.pop', 'Array.prototype.pop')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.pop")}}</p> +</div> + +<h2 id="參見">參見</h2> + +<ul> + <li>{{jsxref("Array.prototype.push()")}}</li> + <li>{{jsxref("Array.prototype.shift()")}}</li> + <li>{{jsxref("Array.prototype.unshift()")}}</li> + <li>{{jsxref("Array.prototype.concat()")}}</li> + <li>{{jsxref("Array.prototype.splice()")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/push/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/push/index.html new file mode 100644 index 0000000000..a506ad15b6 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/push/index.html @@ -0,0 +1,143 @@ +--- +title: Array.prototype.push() +slug: Web/JavaScript/Reference/Global_Objects/Array/push +tags: + - Array + - JavaScript + - Method + - Prototype + - Reference + - 陣列 +translation_of: Web/JavaScript/Reference/Global_Objects/Array/push +--- +<div>{{JSRef}}</div> + +<p><code><strong>push()</strong></code> 方法會添加一個或多個元素至陣列的末端,並且回傳陣列的新長度。</p> + +<div>{{EmbedInteractiveExample("pages/js/array-push.html")}}</div> + + + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox"><var>arr</var>.push(<var>element1</var>[, ...[, <var>elementN</var>]])</pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>element<em>N</em></code></dt> + <dd>欲添加至陣列末端的元素。</dd> +</dl> + +<h3 id="回傳值">回傳值</h3> + +<p>呼叫此方法之物件的新 {{jsxref("Array.length", "length")}} 屬性值。</p> + +<h2 id="描述">描述</h2> + +<p><code>push</code> 方法會將一或多個值加入至一個陣列中。</p> + +<p><code>push</code> 方法被刻意設計為具通用性;此方法可以藉由 {{jsxref("Function.call", "call()")}} 或 {{jsxref("Function.apply", "apply()")}} 應用於類似陣列的物件上。<code>push</code> 方法憑借著物件的 <code>length</code> 屬性來判斷從何處開始插入給定的值。如果 <code>length</code> 屬性無法被轉為數字,則索引值會使用 0。這包括了 <code>length</code> 可能不存在的狀況,在這個情況下 <code>length</code> 屬性也將被建立於物件中。</p> + +<p>唯一的原生類陣列(array-like)物件為{{jsxref("Global_Objects/String", "字串", "", 1)}},但他們不適合用於此方法,因為字串是不可變的(immutable)。</p> + +<h2 id="範例">範例</h2> + +<h3 id="將複數個元素添加至陣列">將複數個元素添加至陣列</h3> + +<p>以下的程式碼會建立含有兩個元素的陣列 <code>sports</code>,接著再增加兩個元素至陣列中。新的長度以變數 <code>total</code> 表示。</p> + +<pre class="brush: js">var sports = ['soccer', 'baseball']; +var total = sports.push('football', 'swimming'); + +console.log(sports); // ['soccer', 'baseball', 'football', 'swimming'] +console.log(total); // 4 +</pre> + +<h3 id="合併兩個陣列">合併兩個陣列</h3> + +<p>這個範例使用 {{jsxref("Function.apply", "apply()")}} 自第二個陣列中增加所有的元素至第一個陣列。</p> + +<p>如果第二個陣列(範例中的 <code>moreVegs</code>)非常大,就不要使用這個方法。因為一個函式能取得的參數之最大數量是受到實作限制的。詳細請參閱 {{jsxref("Function.apply", "apply()")}}。</p> + +<pre class="brush: js">var vegetables = ['parsnip', 'potato']; +var moreVegs = ['celery', 'beetroot']; + +// Merge the second array into the first one +// Equivalent to vegetables.push('celery', 'beetroot'); +Array.prototype.push.apply(vegetables, moreVegs); + +console.log(vegetables); // ['parsnip', 'potato', 'celery', 'beetroot'] +</pre> + +<h3 id="以類陣列(array-like)的方式操作物件">以類陣列(array-like)的方式操作物件</h3> + +<p>正如上面所提到的,<code>push</code> 被刻意設計為具通用性,我們可以善用這個優勢來處理物件。<code>Array.prototype.push</code> 可以在物件上運作良好,如本範例所示。請注意,我們不會建立一個陣列來儲存收集到的物件。相反地,我們將物件集合(collection)儲存於物件自己身上,並使用 <code>call</code> 來呼叫<code>Array.prototype.push</code> 使其認為我們正在處理一個陣列,讓方法可以繼續運作。感謝 JavaScript 允許我們使用這個方式去執行上下文。</p> + +<pre class="brush: js">var obj = { + length: 0, + + addElem: function addElem(elem) { + // obj.length is automatically incremented + // every time an element is added. + [].push.call(this, elem); + } +}; + +// Let's add some empty objects just to illustrate. +obj.addElem({}); +obj.addElem({}); +console.log(obj.length); +// → 2 +</pre> + +<p>請注意雖然 <code>obj</code> 不是一個陣列,但 <code>push</code> 方法成功增加了 <code>obj</code> 的 <code>length</code> 屬性,就像我們在處理一個真正的陣列一樣。</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('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Initial definition. Implemented in JavaScript 1.2.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.7', 'Array.prototype.push')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.push', 'Array.prototype.push')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.push', 'Array.prototype.push')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器支援度">瀏覽器支援度</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.push")}}</p> +</div> + +<h2 id="參見">參見</h2> + +<ul> + <li>{{jsxref("Array.prototype.pop()")}}</li> + <li>{{jsxref("Array.prototype.shift()")}}</li> + <li>{{jsxref("Array.prototype.unshift()")}}</li> + <li>{{jsxref("Array.prototype.concat()")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/reduce/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/reduce/index.html new file mode 100644 index 0000000000..1f943d8dfa --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/reduce/index.html @@ -0,0 +1,472 @@ +--- +title: Array.prototype.reduce() +slug: Web/JavaScript/Reference/Global_Objects/Array/Reduce +tags: + - Array + - ECMAScript 5 + - JavaScript + - Method + - Prototype + - Reduce + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/Reduce +--- +<div>{{JSRef}}</div> + +<p><code><strong>reduce()</strong></code> 方法將一個累加器及陣列中每項元素(由左至右)傳入回呼函式,將陣列化為單一值。</p> + +<div>{{EmbedInteractiveExample("pages/js/array-reduce.html")}}</div> + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox"><var>arr</var>.reduce(<var>callback[accumulator, currentValue, currentIndex, array], </var><var>initialValue</var>)</pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>callback</code></dt> + <dd>用於處理陣列中每個元素的函式,可傳入四個參數: + <dl> + <dt><code>accumulator</code></dt> + <dd>用來累積回呼函式回傳值的累加器(accumulator)或 <code>initialValue</code>(若有提供的話,詳如下敘)。累加器是上一次呼叫後,所回傳的累加數值。</dd> + <dt><code>currentValue</code></dt> + <dd>原陣列目前所迭代處理中的元素。</dd> + <dt><code>currentIndex</code>{{optional_inline}}</dt> + <dd>原陣列目前所迭代處理中的元素之索引。若有傳入 <code>initialValue</code>,則由索引 0 之元素開始,若無則自索引 1 之元素開始。</dd> + <dt><code>array</code>{{optional_inline}}</dt> + <dd>呼叫 <code>reduce()</code> 方法的陣列。</dd> + </dl> + </dd> + <dt><code>initialValue</code>{{optional_inline}}</dt> + <dd>於第一次呼叫 <code>callback</code> 時要傳入的累加器初始值。若沒有提供初始值,則原陣列的第一個元素將會被當作初始的累加器。假如於一個空陣列呼叫 <code>reduce()</code> 方法且沒有提供累加器初始值,將會發生錯誤。</dd> +</dl> + +<h3 id="回傳值">回傳值</h3> + +<p>簡化後的結果值。</p> + +<h2 id="描述">描述</h2> + +<p><code>reduce()</code> 會對每一個目前迭代到的陣列元素(除了空值以外)執行 <code>callback</code> 函式,回呼函式會接收四個參數:</p> + +<ul> + <li><code>accumulator</code></li> + <li><code>currentValue</code></li> + <li><code>currentIndex</code></li> + <li><code>array</code></li> +</ul> + +<p>當回呼函式第一次被呼叫時,<code>accumulator</code> 與 <code>currentValue</code> 的值可能為兩種不同的狀況:若在呼叫 <code>reduce()</code> 時有提供 <code>initialValue</code>,則 <code>accumulator</code> 將會等於 <code>initialValue</code>,且 <code>currentValue</code> 會等於陣列中的第一個元素值;若沒有提供 <code>initialValue</code>,則 <code>accumulator</code> 會等於陣列的第一個元素值,且 <code>currentValue</code> 將會等於陣列的第二個元素值。</p> + +<div class="note"> +<p><strong>備註:</strong>假如 <code>initialValue</code> 未被提供,<code>reduce()</code> 將會跳過第一個陣列索引,從陣列索引 1 開始執行回呼函式。若有提供 <code>initialValue</code>,則會由陣列索引 0 開始執行。</p> +</div> + +<p>若陣列為空且沒有提供 <code>initialValue</code>,將會拋出 {{jsxref("TypeError")}}。假如陣列只有一個元素(無論其索引位置為何)並且沒有提供 <code>initialValue</code>,或如果提供了 <code>initialValue</code> 但陣列為空,則此唯一的值將會被直接回傳<em>而不會呼叫 <code>callback</code> 函式</em>。</p> + +<p>提供累加器初始值通常較為安全,因為在沒有傳入 <code>initialValue</code> 的情況下會有三種可能的輸出結果,如下列範例:</p> + +<pre class="brush: js">var maxCallback = ( acc, cur ) => Math.max( acc.x, cur.x ); +var maxCallback2 = ( max, cur ) => Math.max( max, cur ); + +// reduce() without initialValue +[ { x: 22 }, { x: 42 } ].reduce( maxCallback ); // 42 +[ { x: 22 } ].reduce( maxCallback ); // { x: 22 } +[ ].reduce( maxCallback ); // TypeError + +// map/reduce; better solution, also works for empty or larger arrays +[ { x: 22 }, { x: 42 } ].map( el => el.x ) + .reduce( maxCallback2, -Infinity ); +</pre> + +<h3 id="reduce()_如何運作">reduce() 如何運作</h3> + +<p>假設 <code>reduce()</code> 以下例方式使用:</p> + +<pre class="brush: js">[0, 1, 2, 3, 4].reduce( + function ( +<code> accumulator,</code> + <code>currentValue</code>, + <code>currentIndex</code>, + array + ) { + return <code>accumulator</code> + currentValue; + } +); +</pre> + +<p>所傳入的回呼函式將被呼叫四次,所傳入的參數與回傳值如下所示:</p> + +<table> + <thead> + <tr> + <th scope="col"><code>callback</code></th> + <th scope="col"><code>accumulator</code></th> + <th scope="col"><code>currentValue</code></th> + <th scope="col"><code>currentIndex</code></th> + <th scope="col"><code>array</code></th> + <th scope="col">return value</th> + </tr> + </thead> + <tbody> + <tr> + <th scope="row">first call</th> + <td><code>0</code></td> + <td><code>1</code></td> + <td><code>1</code></td> + <td><code>[0, 1, 2, 3, 4]</code></td> + <td><code>1</code></td> + </tr> + <tr> + <th scope="row">second call</th> + <td><code>1</code></td> + <td><code>2</code></td> + <td><code>2</code></td> + <td><code>[0, 1, 2, 3, 4]</code></td> + <td><code>3</code></td> + </tr> + <tr> + <th scope="row">third call</th> + <td><code>3</code></td> + <td><code>3</code></td> + <td><code>3</code></td> + <td><code>[0, 1, 2, 3, 4]</code></td> + <td><code>6</code></td> + </tr> + <tr> + <th scope="row">fourth call</th> + <td><code>6</code></td> + <td><code>4</code></td> + <td><code>4</code></td> + <td><code>[0, 1, 2, 3, 4]</code></td> + <td><code>10</code></td> + </tr> + </tbody> +</table> + +<p><code>reduce()</code> 的最終回傳值將會是最後一次呼叫回呼函式的回傳值 (<code>10</code>)。</p> + +<p>你也可以傳入一個{{jsxref("Functions/Arrow_functions", "箭頭函式","",1)}}來替代一個完整的函式。下方的程式碼執行的結果將與前述例子相同。</p> + +<pre class="brush: js">[0, 1, 2, 3, 4].reduce( (prev, curr) => prev + curr ); +</pre> + +<p>如果你有提供第二個參數值給 <code>reduce()</code>,執行的結果如下:</p> + +<pre class="brush: js">[0, 1, 2, 3, 4].reduce( + (<code>accumulator</code>, currentValue, currentIndex, array) => { + return <code>accumulator</code> + currentValue; + }, + 10 +); +</pre> + +<table> + <thead> + <tr> + <th scope="col"><code>callback</code></th> + <th scope="col"><code>accumulator</code></th> + <th scope="col"><code>currentValue</code></th> + <th scope="col"><code>currentIndex</code></th> + <th scope="col"><code>array</code></th> + <th scope="col">return value</th> + </tr> + </thead> + <tbody> + <tr> + <th scope="row">first call</th> + <td><code>10</code></td> + <td><code>0</code></td> + <td><code>0</code></td> + <td><code>[0, 1, 2, 3, 4]</code></td> + <td><code>10</code></td> + </tr> + <tr> + <th scope="row">second call</th> + <td><code>10</code></td> + <td><code>1</code></td> + <td><code>1</code></td> + <td><code>[0, 1, 2, 3, 4]</code></td> + <td><code>11</code></td> + </tr> + <tr> + <th scope="row">third call</th> + <td><code>11</code></td> + <td><code>2</code></td> + <td><code>2</code></td> + <td><code>[0, 1, 2, 3, 4]</code></td> + <td><code>13</code></td> + </tr> + <tr> + <th scope="row">fourth call</th> + <td><code>13</code></td> + <td><code>3</code></td> + <td><code>3</code></td> + <td><code>[0, 1, 2, 3, 4]</code></td> + <td><code>16</code></td> + </tr> + <tr> + <th scope="row">fifth call</th> + <td><code>16</code></td> + <td><code>4</code></td> + <td><code>4</code></td> + <td><code>[0, 1, 2, 3, 4]</code></td> + <td><code>20</code></td> + </tr> + </tbody> +</table> + +<p><code>reduce()</code> 執行的結果將會是 <code>20</code>。</p> + +<h2 id="範例">範例</h2> + +<h3 id="加總所有陣例之元素值">加總所有陣例之元素值</h3> + +<pre class="brush: js">var sum = [0, 1, 2, 3].reduce(function (a, b) { + return a + b; +}, 0); +// sum is 6 +</pre> + +<p>另外,也可以寫成箭頭函式:</p> + +<pre class="brush: js">var total = [ 0, 1, 2, 3 ].reduce( + ( acc, cur ) => acc + cur, + 0 +);</pre> + +<h3 id="攤平一個多維陣列">攤平一個多維陣列</h3> + +<pre class="brush: js">var flattened = [[0, 1], [2, 3], [4, 5]].reduce( + function(a, b) { + return a.concat(b); + }, + [] +); +// flattened is [0, 1, 2, 3, 4, 5] +</pre> + +<p>另外,也可以寫成箭頭函式:</p> + +<pre class="brush: js">var flattened = [[0, 1], [2, 3], [4, 5]].reduce( + ( acc, cur ) => acc.concat(cur), + [] +); +</pre> + +<h3 id="計算相同元素數量並以物件鍵值顯示">計算相同元素數量並以物件鍵值顯示</h3> + +<pre class="brush: js">var names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice']; + +var countedNames = names.reduce(function (allNames, name) { + if (name in allNames) { + allNames[name]++; + } + else { + allNames[name] = 1; + } + return allNames; +}, {}); +// countedNames is: +// { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 } +</pre> + +<h3 id="使用_spread_運算子與給定初始值,結合物件中的陣列元素">使用 spread 運算子與給定初始值,結合物件中的陣列元素</h3> + +<pre class="brush: js">// friends - an array of objects +// where object field "books" - list of favorite books +var friends = [{ + name: 'Anna', + books: ['Bible', 'Harry Potter'], + age: 21 +}, { + name: 'Bob', + books: ['War and peace', 'Romeo and Juliet'], + age: 26 +}, { + name: 'Alice', + books: ['The Lord of the Rings', 'The Shining'], + age: 18 +}]; + +// allbooks - list which will contain all friends' books + +// additional list contained in initialValue +var allbooks = friends.reduce(function(prev, curr) { + return [...prev, ...curr.books]; +}, ['Alphabet']); + +// allbooks = [ +// 'Alphabet', 'Bible', 'Harry Potter', 'War and peace', +// 'Romeo and Juliet', 'The Lord of the Rings', +// 'The Shining' +// ]</pre> + +<p> </p> + +<h3 id="移除陣列中的重複項目">移除陣列中的重複項目</h3> + +<pre class="brush: js">let arr = [1, 2, 1, 2, 3, 5, 4, 5, 3, 4, 4, 4, 4]; +let result = arr.sort().reduce((init, current) => { + if (init.length === 0 || init[init.length - 1] !== current) { + init.push(current); + } + return init; +}, []); +console.log(result); //[1,2,3,4,5] +</pre> + +<h3 id="序列執行_Promise">序列執行 Promise</h3> + +<pre class="brush: js">/** + * Runs promises from promise array in chained manner + * + * @param {array} arr - promise arr + * @return {Object} promise object + */ +function runPromiseInSequense(arr) { + return arr.reduce((promiseChain, currentPromise) => { + return promiseChain.then((chainedResult) => { + return currentPromise(chainedResult) + .then((res) => res) + }) + }, Promise.resolve()); +} + +// promise function 1 +function p1() { + return new Promise((resolve, reject) => { + resolve(5); + }); +} + +// promise function 2 +function p2(a) { + return new Promise((resolve, reject) => { + resolve(a * 2); + }); +} + +// promise function 3 +function p3(a) { + return new Promise((resolve, reject) => { + resolve(a * 3); + }); +} + +const promiseArr = [p1, p2, p3]; +runPromiseInSequense(promiseArr) + .then((res) => { + console.log(res); // 30 + }); + +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<pre class="brush: js">// Production steps of ECMA-262, Edition 5, 15.4.4.21 +// Reference: http://es5.github.io/#x15.4.4.21 +// https://tc39.github.io/ecma262/#sec-array.prototype.reduce +if (!Array.prototype.reduce) { + Object.defineProperty(Array.prototype, 'reduce', { + value: function(callback /*, initialValue*/) { + if (this === null) { + throw new TypeError( 'Array.prototype.reduce ' + + 'called on null or undefined' ); + } + if (typeof callback !== 'function') { + throw new TypeError( callback + + ' is not a function'); + } + + // 1. Let O be ? ToObject(this value). + var o = Object(this); + + // 2. Let len be ? ToLength(? Get(O, "length")). + var len = o.length >>> 0; + + // Steps 3, 4, 5, 6, 7 + var k = 0; + var value; + + if (arguments.length >= 2) { + value = arguments[1]; + } else { + while (k < len && !(k in o)) { + k++; + } + + // 3. If len is 0 and initialValue is not present, + // throw a TypeError exception. + if (k >= len) { + throw new TypeError( 'Reduce of empty array ' + + 'with no initial value' ); + } + value = o[k++]; + } + + // 8. Repeat, while k < len + while (k < len) { + // a. Let Pk be ! ToString(k). + // b. Let kPresent be ? HasProperty(O, Pk). + // c. If kPresent is true, then + // i. Let kValue be ? Get(O, Pk). + // ii. Let accumulator be ? Call( + // callbackfn, undefined, + // « accumulator, kValue, k, O »). + if (k in o) { + value = callback(value, o[k], k, o); + } + + // d. Increase k by 1. + k++; + } + + // 9. Return accumulator. + return value; + } + }); +} +</pre> + +<p>如果還需要支援老舊到不支援 <code><a href="/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty">Object.defineProperty</a></code> 的 JavaScript 引擎,最好不要 polyfill <code>Array.prototype</code> 方法,因為你無法令其不可枚舉(non-enumerable)。</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('ES5.1', '#sec-15.4.4.21', 'Array.prototype.reduce()')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.8.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.reduce', 'Array.prototype.reduce()')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.reduce', 'Array.prototype.reduce()')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.reduce")}}</p> +</div> + +<h2 id="參見">參見</h2> + +<ul> + <li>{{jsxref("Array.prototype.reduceRight()")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/reverse/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/reverse/index.html new file mode 100644 index 0000000000..d3104c28be --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/reverse/index.html @@ -0,0 +1,90 @@ +--- +title: Array.prototype.reverse() +slug: Web/JavaScript/Reference/Global_Objects/Array/reverse +tags: + - Array + - JavaScript + - Method + - Prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Array/reverse +--- +<div>{{JSRef}}</div> + +<p><code><strong>reverse()</strong></code> 方法會<em><a href="https://zh.wikipedia.org/wiki/%E5%8E%9F%E5%9C%B0%E7%AE%97%E6%B3%95">原地(in place)</a></em>反轉(reverses)一個陣列。陣列中的第一個元素變為最後一個,而最後一個元素則變成第一個。</p> + +<div>{{EmbedInteractiveExample("pages/js/array-reverse.html")}}</div> + + + +<h2 id="Syntax" name="Syntax">語法</h2> + +<pre class="syntaxbox"><var>a</var>.reverse()</pre> + +<h3 id="回傳值">回傳值</h3> + +<p>反轉後的陣列。</p> + +<h2 id="Description" name="Description">描述</h2> + +<p><code>reverse</code> 方法將原地(in place)變換(transposes)呼叫此方法的陣列物件之元素至其顛倒的位置,改變原陣列後,並回傳此陣列之參考位址(reference)。</p> + +<h2 id="Examples" name="Examples">範例</h2> + +<h3 id="Example:_Reversing_the_elements_in_an_array" name="Example:_Reversing_the_elements_in_an_array">反轉陣列中之元素</h3> + +<p>下列範例建立了一個包含三個元素的陣列 <code>a</code>,接著反轉此陣列。呼叫 <code>reverse()</code> 會回傳一個反轉後的原陣列 <code>a</code> 之參考。</p> + +<pre class="brush: js">var a = ['one', 'two', 'three']; +var reversed = a.reverse(); + +console.log(a); // ['three', 'two', 'one'] +console.log(reversed); // ['three', 'two', 'one'] +</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>Initial definition. Implemented in JavaScript 1.1.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.8', 'Array.prototype.reverse')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.reverse', 'Array.prototype.reverse')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.reverse', 'Array.prototype.reverse')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.reverse")}}</p> +</div> + +<h2 id="參見">參見</h2> + +<ul> + <li>{{jsxref("Array.prototype.join()")}}</li> + <li>{{jsxref("Array.prototype.sort()")}}</li> + <li>{{jsxref("TypedArray.prototype.reverse()")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/shift/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/shift/index.html new file mode 100644 index 0000000000..269dfac4fe --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/shift/index.html @@ -0,0 +1,114 @@ +--- +title: Array.prototype.shift() +slug: Web/JavaScript/Reference/Global_Objects/Array/shift +tags: + - Array + - JavaScript + - Method + - Prototype + - shift + - 陣列 +translation_of: Web/JavaScript/Reference/Global_Objects/Array/shift +--- +<div>{{JSRef}}</div> + +<p><code><strong>shift()</strong></code> 方法會移除並回傳陣列的<strong>第一個</strong>元素。此方法會改變陣列的長度。</p> + +<div>{{EmbedInteractiveExample("pages/js/array-shift.html")}}</div> + + + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox"><var>arr</var>.shift()</pre> + +<h3 id="回傳值">回傳值</h3> + +<p>自陣列中移除的元素;若陣列為空,則為 {{jsxref("undefined")}}。</p> + +<h2 id="描述">描述</h2> + +<p><code>shift</code> 方法會移除並回傳陣列中索引值為零之元素(即第一個元素),並將隨後的其他索引值減一。假如 {{jsxref("Array.length", "length")}} 屬性值為 0,則會回傳 {{jsxref("undefined")}}。</p> + +<p><code>shift</code> 方法被刻意設計為具通用性;此方法可以藉由 {{jsxref("Function.call", "called", "", 1)}} 或 {{jsxref("Function.apply", "applied", "", 1)}} 應用於類似陣列的物件上。若欲應用此方法的物件不包含代表一系列啟始為零之數字屬性序列長度的 <code>length</code> 屬性,可能是不具任何意義的行為。</p> + +<h2 id="範例">範例</h2> + +<h3 id="自陣列中移除一個元素">自陣列中移除一個元素</h3> + +<p>以下的程式碼會印出 <code>myFish</code> 陣列在移除第一個元素之前跟之後的內容,也印出了被移除的元素:</p> + +<pre class="brush: js">var myFish = ['angel', 'clown', 'mandarin', 'surgeon']; + +console.log('myFish before:', JSON.stringify(myFish)); +// myFish before: ['angel', 'clown', 'mandarin', 'surgeon'] + +var shifted = myFish.shift(); + +console.log('myFish after:', myFish); +// myFish after: ['clown', 'mandarin', 'surgeon'] + +console.log('Removed this element:', shifted); +// Removed this element: angel +</pre> + +<h3 id="於_while_迴圈中使用_shift()_方法">於 while 迴圈中使用 shift() 方法</h3> + +<p><code>shift()</code> 方法常被用在 while 迴圈中的條件判斷。在下面的例子,每一次迭代都將會自陣列中移除下一個元素,直到陣列空了為止:</p> + +<pre class="brush: js">var names = ["Andrew", "Edward", "Paul", "Chris" ,"John"]; + +while( (i = names.shift()) !== undefined ) { + console.log(i); +} +// Andrew, Edward, Paul, Chris, John +</pre> + +<h2 id="規範">規範</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Initial definition. Implemented in JavaScript 1.2.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.9', 'Array.prototype.shift')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.shift', 'Array.prototype.shift')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.shift', 'Array.prototype.shift')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.shift")}}</p> +</div> + +<h2 id="參見">參見</h2> + +<ul> + <li>{{jsxref("Array.prototype.push()")}}</li> + <li>{{jsxref("Array.prototype.pop()")}}</li> + <li>{{jsxref("Array.prototype.unshift()")}}</li> + <li>{{jsxref("Array.prototype.concat()")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/slice/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/slice/index.html new file mode 100644 index 0000000000..e9cb1fb02c --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/slice/index.html @@ -0,0 +1,242 @@ +--- +title: Array.prototype.slice() +slug: Web/JavaScript/Reference/Global_Objects/Array/slice +tags: + - Array + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/slice +--- +<div>{{JSRef}}</div> + +<p><code><strong>slice()</strong></code> 方法會回傳一個新陣列物件,為原陣列選擇之 <code>begin</code> 至 <code>end</code>(不含 <code>end</code>)部分的淺拷貝(shallow copy)。而原本的陣列將不會被修改。</p> + +<div>{{EmbedInteractiveExample("pages/js/array-slice.html")}}</div> + +<p class="hidden">The source for this interactive demo is stored in a GitHub repository. If you'd like to contribute to the interactive demo project, please clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> and send us a pull request.</p> + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox notranslate"><var>arr</var>.slice(<em>[</em><var>begin[</var>, <var>end]]</var>) +</pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>begin</code> {{optional_inline}}</dt> + <dd>自哪一個索引(起始為 0)開始提取拷貝。</dd> + <dd>可使用負數索引,表示由陣列的最末項開始提取。<code>slice(-2)</code> 代表拷貝陣列中的最後兩個元素。</dd> + <dd>假如 <code>begin</code> 為 undefined,則 <code>slice</code> 會從索引 <code>0</code> 開始提取。</dd> + <dt><code>end</code> {{optional_inline}}</dt> + <dd>至哪一個索引(起始為 0)<em>之前</em>停止提取。<code>slice</code> 提取但不包含至索引 <code>end</code>。</dd> + <dd>舉例來說,<code>slice(1,4)</code> 提取了陣列中第二個元素至第四個元素前為止(元素索引 1、2 以及 3)來拷貝。</dd> + <dd>可使用負數索引,表示由陣列的最末項開始提取。<code>slice(2,-1)</code> 代表拷貝陣列中第三個元素至倒數第二個元素。</dd> + <dd>若省略了 <code>end</code>,則 <code>slice</code> 會提取至陣列的最後一個元素(<code>arr.length</code>)。</dd> + <dd>假如 <code>end</code> 大於陣列的長度,<code>slice</code> 會提取至陣列的最後一個元素(<code>arr.length</code>)。</dd> +</dl> + +<h3 id="回傳值">回傳值</h3> + +<p>一個包含提取之元素的新陣列。</p> + +<h2 id="說明">說明</h2> + +<p><code>slice</code> 不會修改原本的陣列,而是回傳由原本的陣列淺層複製的元素。原始陣列的元素會按照下列規則拷貝:</p> + +<ul> + <li>如果該元素是個對象引用(不是實際的對象),<code>slice</code> 會拷貝這個對象引用到新的陣列內。兩個對象引用都引用了同一個對象。如果被引用的對象發生改變,則新的和原來的陣列中的這個元素也會發生改變。</li> + <li>對於字串、數字、布林來說 (不是 <a href="https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/String"><code>String</code></a>、<a href="https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Number"><code>Number</code></a> 或者 <a href="https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Boolean"><code>Boolean</code></a> 對象), <code>slice</code> 會拷貝這些值到新的陣列內。在別的陣列內修改這些字串、數字或是布林,將不會影響另一個陣列。</li> +</ul> + +<p>如果添加了新的元素到另一個陣列內,則另一個不會受到影響。</p> + +<h2 id="範例">範例</h2> + +<h3 id="Return_a_portion_of_an_existing_array">Return a portion of an existing array</h3> + +<pre class="brush: js notranslate">var fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']; +var citrus = fruits.slice(1, 3); + +// fruits contains ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'] +// citrus contains ['Orange','Lemon'] +</pre> + +<h3 id="Using_slice">Using <code>slice</code></h3> + +<p>In the following example, <code>slice</code> creates a new array, <code>newCar</code>, from <code>myCar</code>. Both include a reference to the object <code>myHonda</code>. When the color of <code>myHonda</code> is changed to purple, both arrays reflect the change.</p> + +<pre class="brush: js notranslate">// Using slice, create newCar from myCar. +var myHonda = { color: 'red', wheels: 4, engine: { cylinders: 4, size: 2.2 } }; +var myCar = [myHonda, 2, 'cherry condition', 'purchased 1997']; +var newCar = myCar.slice(0, 2); + +// Display the values of myCar, newCar, and the color of myHonda +// referenced from both arrays. +console.log('myCar = ' + JSON.stringify(myCar)); +console.log('newCar = ' + JSON.stringify(newCar)); +console.log('myCar[0].color = ' + myCar[0].color); +console.log('newCar[0].color = ' + newCar[0].color); + +// Change the color of myHonda. +myHonda.color = 'purple'; +console.log('The new color of my Honda is ' + myHonda.color); + +// Display the color of myHonda referenced from both arrays. +console.log('myCar[0].color = ' + myCar[0].color); +console.log('newCar[0].color = ' + newCar[0].color); +</pre> + +<p>This script writes:</p> + +<pre class="brush: js notranslate">myCar = [{color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}}, 2, + 'cherry condition', 'purchased 1997'] +newCar = [{color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}}, 2] +myCar[0].color = red +newCar[0].color = red +The new color of my Honda is purple +myCar[0].color = purple +newCar[0].color = purple +</pre> + +<h2 id="類陣例(Array-like)物件">類陣例(Array-like)物件</h2> + +<p><code>slice</code> method can also be called to convert Array-like objects / collections to a new Array. You just bind the method to the object. The {{jsxref("Functions/arguments", "arguments")}} inside a function is an example of an 'array-like object'.</p> + +<pre class="brush: js notranslate">function list() { + return Array.prototype.slice.call(arguments); +} + +var list1 = list(1, 2, 3); // [1, 2, 3] +</pre> + +<p>Binding can be done with the .<code>call</code> function of {{jsxref("Function.prototype")}} and it can also be reduced using <code>[].slice.call(arguments)</code> instead of <code>Array.prototype.slice.call</code>. Anyway, it can be simplified using {{jsxref("Function.prototype.bind", "bind")}}.</p> + +<pre class="brush: js notranslate">var unboundSlice = Array.prototype.slice; +var slice = Function.prototype.call.bind(unboundSlice); + +function list() { + return slice(arguments); +} + +var list1 = list(1, 2, 3); // [1, 2, 3] +</pre> + +<h2 id="Streamlining_cross-browser_behavior">Streamlining cross-browser behavior</h2> + +<p>Although host objects (such as DOM objects) are not required by spec to follow the Mozilla behavior when converted by <code>Array.prototype.slice</code> and IE < 9 does not do so, versions of IE starting with version 9 do allow this. “Shimming” it can allow reliable cross-browser behavior. As long as other modern browsers continue to support this ability, as currently do IE, Mozilla, Chrome, Safari, and Opera, developers reading (DOM-supporting) slice code relying on this shim will not be misled by the semantics; they can safely rely on the semantics to provide the now apparently <em>de facto</em> standard behavior. (The shim also fixes IE to work with the second argument of <code>slice()</code> being an explicit {{jsxref("null")}}/{{jsxref("undefined")}} value as earlier versions of IE also did not allow but all modern browsers, including IE >= 9, now do.)</p> + +<pre class="brush: js notranslate">/** + * Shim for "fixing" IE's lack of support (IE < 9) for applying slice + * on host objects like NamedNodeMap, NodeList, and HTMLCollection + * (technically, since host objects have been implementation-dependent, + * at least before ES2015, IE hasn't needed to work this way). + * Also works on strings, fixes IE < 9 to allow an explicit undefined + * for the 2nd argument (as in Firefox), and prevents errors when + * called on other DOM objects. + */ +(function () { + 'use strict'; + var _slice = Array.prototype.slice; + + try { + // Can't be used with DOM elements in IE < 9 + _slice.call(document.documentElement); + } catch (e) { // Fails in IE < 9 + // This will work for genuine arrays, array-like objects, + // NamedNodeMap (attributes, entities, notations), + // NodeList (e.g., getElementsByTagName), HTMLCollection (e.g., childNodes), + // and will not fail on other DOM objects (as do DOM elements in IE < 9) + Array.prototype.slice = function(begin, end) { + // IE < 9 gets unhappy with an undefined end argument + end = (typeof end !== 'undefined') ? end : this.length; + + // For native Array objects, we use the native slice function + if (Object.prototype.toString.call(this) === '[object Array]'){ + return _slice.call(this, begin, end); + } + + // For array like object we handle it ourselves. + var i, cloned = [], + size, len = this.length; + + // Handle negative value for "begin" + var start = begin || 0; + start = (start >= 0) ? start : Math.max(0, len + start); + + // Handle negative value for "end" + var upTo = (typeof end == 'number') ? Math.min(end, len) : len; + if (end < 0) { + upTo = len + end; + } + + // Actual expected size of the slice + size = upTo - start; + + if (size > 0) { + cloned = new Array(size); + if (this.charAt) { + for (i = 0; i < size; i++) { + cloned[i] = this.charAt(start + i); + } + } else { + for (i = 0; i < size; i++) { + cloned[i] = this[start + i]; + } + } + } + + return cloned; + }; + } +}()); +</pre> + +<h2 id="規範">規範</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Initial definition. Implemented in JavaScript 1.2.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.10', 'Array.prototype.slice')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.slice', 'Array.prototype.slice')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.slice', 'Array.prototype.slice')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.slice")}}</p> +</div> + +<h2 id="參見">參見</h2> + +<ul> + <li>{{jsxref("Array.prototype.splice()")}}</li> + <li>{{jsxref("Function.prototype.call()")}}</li> + <li>{{jsxref("Function.prototype.bind()")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/some/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/some/index.html new file mode 100644 index 0000000000..7dd0fbdf34 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/some/index.html @@ -0,0 +1,217 @@ +--- +title: Array.prototype.some() +slug: Web/JavaScript/Reference/Global_Objects/Array/some +tags: + - Array + - ECMAScript5 + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/some +--- +<div>{{JSRef}}</div> + +<p><code><strong>some()</strong></code> 方法會透過給定函式、測試陣列中是否至少有一個元素,通過該函式所實作的測試。這方法回傳的是布林值。</p> + +<div>{{EmbedInteractiveExample("pages/js/array-some.html")}}</div> + +<div class="note"> +<p><strong>注意</strong>:如果輸入空陣列的話,這個方法會回傳 <code>false</code>。</p> +</div> + + + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox"><var>arr</var>.some(<var>callback</var>[, <var>thisArg</var>])</pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>callback</code></dt> + <dd>用來測試每一個元素的函式,它包含三個引數: + <dl> + <dt><code>currentValue</code></dt> + <dd>目前正要被處理的陣列元素。</dd> + <dt><code>index{{Optional_inline}}</code></dt> + <dd>目前正要被處理的陣列元素之索引值。</dd> + <dt><code>array{{Optional_inline}}</code></dt> + <dd>呼叫 <code>some()</code> 的陣列。</dd> + </dl> + </dd> + <dt><code>thisArg{{Optional_inline}}</code></dt> + <dd>執行 <code>callback</code> 回呼函式的 <code>this</code> 值。</dd> +</dl> + +<h3 id="回傳值">回傳值</h3> + +<p>若回呼函式在處理任何一個陣列元素時得到 {{Glossary("truthy")}} 值,則回傳 <code><strong>true</strong></code>。否則,回傳值為 <code><strong>false</strong></code>。</p> + +<h2 id="描述">描述</h2> + +<p>The <code>some()</code> method executes the <code>callback</code> function once for each element present in the array until it finds the one where <code>callback</code> returns a <em>truthy</em> value (a value that becomes true when converted to a Boolean). If such an element is found, <code>some()</code> immediately returns <code>true</code>. Otherwise, <code>some()</code> returns <code>false</code>. <code>callback</code> is invoked only for indexes of the array with assigned values. It is not invoked for indexes which have been deleted or which have never been assigned values.</p> + +<p><code>callback</code> is invoked with three arguments: the value of the element, the index of the element, and the Array object being traversed.</p> + +<p>If a <code>thisArg</code> parameter is provided to <code>some()</code>, it will be used as the callback's <code>this</code> value. Otherwise, the value {{jsxref("undefined")}} will be used as its <code>this</code> value. The <code>this</code> value ultimately observable by <code>callback</code> is determined according to <a href="/en-US/docs/Web/JavaScript/Reference/Operators/this">the usual rules for determining the <code>this</code> seen by a function</a>.</p> + +<p><code>some()</code> does not mutate the array on which it is called.</p> + +<p>The range of elements processed by <code>some()</code> is set before the first invocation of <code>callback</code>. Elements appended to the array after the call to <code>some()</code> begins will not be visited by <code>callback</code>. If an existing, unvisited element of the array is changed by <code>callback</code>, its value passed to the visiting <code>callback</code> will be the value at the time that <code>some()</code> visits that element's index. Elements that are deleted are not visited.</p> + +<h2 id="範例">範例</h2> + +<h3 id="測試陣列元素的數值">測試陣列元素的數值</h3> + +<p>以下範例將測試是否最少有一個元素的數值大於 10。</p> + +<pre class="brush: js">function isBiggerThan10(element, index, array) { + return element > 10; +} + +[2, 5, 8, 1, 4].some(isBiggerThan10); // false +[12, 5, 8, 1, 4].some(isBiggerThan10); // true</pre> + +<p>{{ EmbedLiveSample('Testing_value_of_array_elements', '', '', '', 'Web/JavaScript/Reference/Global_Objects/Array/some') }}</p> + +<h3 id="使用箭頭函式測試">使用箭頭函式測試</h3> + +<p><a href="/zh-TW/docs/Web/JavaScript/Reference/Functions/Arrow_functions">箭頭函式</a>能給相同的測試,提供更簡潔的語法。</p> + +<pre class="brush: js">[2, 5, 8, 1, 4].some(x => x > 10); //false +[12, 5, 8, 1, 4].some(x => x > 10); // true</pre> + +<p>{{ EmbedLiveSample('Testing_array_elements_using_arrow_functions', '', '', '', 'Web/JavaScript/Reference/Global_Objects/Array/some') }}</p> + +<h3 id="測試陣列元素的數值是否存在">測試陣列元素的數值是否存在</h3> + +<p>To mimic the function of the <code>includes()</code> method, this custom function returns <code>true</code> if the element exists in the array:</p> + +<pre class="brush: js">const fruits = ['apple', 'banana', 'mango', 'guava']; + +function checkAvailability(arr, val) { + return arr.some(function(arrVal) { + return val === arrVal; + }); +} + +checkAvailability(fruits, 'kela'); // false +checkAvailability(fruits, 'banana'); // true</pre> + +<p>{{ EmbedLiveSample('Checking_whether_a_value_exists_in_an_array', '', '', '', 'Web/JavaScript/Reference/Global_Objects/Array/some') }}</p> + +<h3 id="Checking_whether_a_value_exists_using_an_arrow_function">Checking whether a value exists using an arrow function</h3> + +<pre class="brush: js">const fruits = ['apple', 'banana', 'mango', 'guava']; + +function checkAvailability(arr, val) { + return arr.some(arrVal => val === arrVal); +} + +checkAvailability(fruits, 'kela'); // false +checkAvailability(fruits, 'banana'); // true</pre> + +<p>{{ EmbedLiveSample('Checking_whether_a_value_exists_using_an_arrow_function', '', '', '', 'Experiment:StaticExamplesOnTop/JavaScript/Array/some') }}</p> + +<h3 id="Converting_any_value_to_Boolean">Converting any value to Boolean</h3> + +<pre class="brush: js">const TRUTHY_VALUES = [true, 'true', 1]; + +function getBoolean(value) { + 'use strict'; + + if (typeof value === 'string') { + value = value.toLowerCase().trim(); + } + + return TRUTHY_VALUES.some(function(t) { + return t === value; + }); +} + +getBoolean(false); // false +getBoolean('false'); // false +getBoolean(1); // true +getBoolean('true'); // true</pre> + +<p>{{ EmbedLiveSample('Converting_any_value_to_Boolean', '', '', '', 'Web/JavaScript/Reference/Global_Objects/Array/some') }}</p> + +<h2 id="Polyfill">Polyfill</h2> + +<p><code>some()</code> was added to the ECMA-262 standard in the 5th edition, and it may not be present in all implementations of the standard. You can work around this by inserting the following code at the beginning of your scripts, allowing use of <code>some()</code> in implementations which do not natively support it. This algorithm is exactly the one specified in ECMA-262, 5th edition, assuming {{jsxref("Object")}} and {{jsxref("TypeError")}} have their original values and that <code>fun.call</code> evaluates to the original value of {{jsxref("Function.prototype.call()")}}.</p> + +<pre class="brush: js">// Production steps of ECMA-262, Edition 5, 15.4.4.17 +// Reference: http://es5.github.io/#x15.4.4.17 +if (!Array.prototype.some) { + Array.prototype.some = function(fun, thisArg) { + 'use strict'; + + if (this == null) { + throw new TypeError('Array.prototype.some called on null or undefined'); + } + + if (typeof fun !== 'function') { + throw new TypeError(); + } + + var t = Object(this); + var len = t.length >>> 0; + + for (var i = 0; i < len; i++) { + if (i in t && fun.call(thisArg, t[i], i, t)) { + return true; + } + } + + return false; + }; +} +</pre> + +<p>{{ EmbedLiveSample('Polyfill', '', '', '', 'Web/JavaScript/Reference/Global_Objects/Array/some') }}</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('ES5.1', '#sec-15.4.4.17', 'Array.prototype.some')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>初始定義。在 JavaScript 1.6 實作。</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.some', 'Array.prototype.some')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.some', 'Array.prototype.some')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.some")}}</p> +</div> + +<h2 id="參見">參見</h2> + +<ul> + <li>{{jsxref("Array.prototype.forEach()")}}</li> + <li>{{jsxref("Array.prototype.every()")}}</li> + <li>{{jsxref("Array.prototype.find()")}}</li> + <li>{{jsxref("TypedArray.prototype.some()")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/sort/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/sort/index.html new file mode 100644 index 0000000000..7240184a75 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/sort/index.html @@ -0,0 +1,248 @@ +--- +title: Array.prototype.sort() +slug: Web/JavaScript/Reference/Global_Objects/Array/sort +tags: + - Array + - JavaScript + - Method + - Prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Array/sort +--- +<div>{{JSRef}}</div> + +<p><code><strong>sort()</strong></code> 方法會<em><a href="https://zh.wikipedia.org/wiki/%E5%8E%9F%E5%9C%B0%E7%AE%97%E6%B3%95">原地(in place)</a></em>對一個陣列的所有元素進行排序,並回傳此陣列。排序不一定是<a href="https://zh.wikipedia.org/wiki/%E6%8E%92%E5%BA%8F%E7%AE%97%E6%B3%95#%E7%A9%A9%E5%AE%9A%E6%80%A7">穩定的(stable)</a>。預設的排序順序是根據字串的 Unicode 編碼位置(code points)而定。</p> + +<p>由於依賴執行環境的實作,所以並不能保證排序的時間及空間複雜度。</p> + +<div>{{EmbedInteractiveExample("pages/js/array-sort.html")}}</div> + + + +<h2 id="Syntax" name="Syntax">語法</h2> + +<pre class="syntaxbox"><var>arr</var>.sort(<var>[compareFunction]</var>) +</pre> + +<h3 id="Parameters" name="Parameters">參數</h3> + +<dl> + <dt><code>compareFunction</code> {{optional_inline}}</dt> + <dd>指定一個函式來定義排序順序。假如省略此參數,陣列將根據各個元素轉為字串後的每一個字元之 <a href="/zh-TW/docs/Web/JavaScript/Guide/Values,_variables,_and_literals#Unicode">Unicode</a> 編碼位置值進行排序。</dd> +</dl> + +<h3 id="回傳值">回傳值</h3> + +<p>排序後的陣列。請注意此為<em><a href="https://zh.wikipedia.org/wiki/%E5%8E%9F%E5%9C%B0%E7%AE%97%E6%B3%95">原地(in place)</a></em>進行排序過的陣列,並且不是原陣列的拷貝。</p> + +<h2 id="Description" name="Description">描述</h2> + +<p>如果 <code>compareFunction</code> 沒有被應用,元素將被轉換為字串並以 Unicode 編碼位置進行比較來排序。舉例來說,"Banana" 會被排在 "cherry" 之前。在數值排序中,9 排在 80 前面,但因為數字被轉換成字串,在 Unicode 順序中 "80" 會在 "9" 的前面。</p> + +<p>如果 <code>compareFunction</code> 被應用,陣列元素們將根據比較函式之回傳值來排序。如果 <code>a</code> 和 <code>b</code> 為被比較之兩元素,則:</p> + +<ul> + <li>若 <code>compareFunction(a, b)</code> 的回傳值小於 0,則會把 <code>a</code> 排在小於 <code>b</code> 之索引的位置,即 <code>a</code> 排在 <code>b</code> 前面。</li> + <li>若 <code>compareFunction(a, b)</code> 回傳 0,則 <code>a</code> 與 <code>b</code> 皆不會改變彼此的順序,但會與其他全部的元素比較來排序。備註:ECMAscript 標準並不保證這個行為,因此不是所有瀏覽器(如 Mozilla 版本在 2003 以前)都遵守此行為。</li> + <li>若 <code>compareFunction(a, b)</code> 的回傳值大於 0,則會把 <code>b</code> 排在小於 <code>a</code> 之索引的位置,即 <code>b</code> 排在 <code>a</code> 前面。</li> + <li><code>compareFunction(a, b)</code> 在給予一組特定元素 a 及 b 為此函數之兩引數時必須總是回傳相同的值。若回傳值不一致,排序順序則為 undefined。</li> +</ul> + +<p>所以,比較函式會是以下形式:</p> + +<pre class="brush: js">function compare(a, b) { + if (在某排序標準下 a 小於 b) { + return -1; + } + if (在某排序標準下 a 大於 b) { + return 1; + } + // a 必須等於 b + return 0; +} +</pre> + +<p>為了比較數字而不是字串,比較函式可以僅僅利用 <code>a</code> 減 <code>b</code>。以下函式將會升冪排序陣列:</p> + +<pre class="brush: js">function compareNumbers(a, b) { + return a - b; +} +</pre> + +<p><code>sort</code> 方法可以直接使用{{jsxref("Operators/function", "函式運算式", "", 1)}}(以及<a href="/zh-TW/docs/Web/JavaScript/Guide/Closures">閉包(closures)</a>):</p> + +<pre class="brush: js">var numbers = [4, 2, 5, 1, 3]; +numbers.sort(function(a, b) { + return a - b; +}); +console.log(numbers); + +// [1, 2, 3, 4, 5] +</pre> + +<p>物件可以按照其中一個屬性的值來排序。</p> + +<pre class="brush: js">var items = [ + { name: 'Edward', value: 21 }, + { name: 'Sharpe', value: 37 }, + { name: 'And', value: 45 }, + { name: 'The', value: -12 }, + { name: 'Magnetic', value: 13 }, + { name: 'Zeros', value: 37 } +]; + +// sort by value +items.sort(function (a, b) { + return a.value - b.value; +}); + +// sort by name +items.sort(function(a, b) { + var nameA = a.name.toUpperCase(); // ignore upper and lowercase + var nameB = b.name.toUpperCase(); // ignore upper and lowercase + if (nameA < nameB) { + return -1; + } + if (nameA > nameB) { + return 1; + } + + // names must be equal + return 0; +});</pre> + +<h2 id="範例">範例</h2> + +<h3 id="Example:_Creating.2C_displaying.2C_and_sorting_an_array" name="Example:_Creating.2C_displaying.2C_and_sorting_an_array">建立、顯示及排序一個陣列</h3> + +<p>下列範例建立了四個陣列並顯示其原本陣列內容、再進行排序。數字陣列先不使用比較函式(compare function)來排序,接著才依據比較函式進行排序。</p> + +<pre class="brush: js">var stringArray = ['Blue', 'Humpback', 'Beluga']; +var numericStringArray = ['80', '9', '700']; +var numberArray = [40, 1, 5, 200]; +var mixedNumericArray = ['80', '9', '700', 40, 1, 5, 200]; + +function compareNumbers(a, b) { + return a - b; +} + +console.log('stringArray:', stringArray.join()); +console.log('Sorted:', stringArray.sort()); + +console.log('numberArray:', numberArray.join()); +console.log('Sorted without a compare function:', numberArray.sort()); +console.log('Sorted with compareNumbers:', numberArray.sort(compareNumbers)); + +console.log('numericStringArray:', numericStringArray.join()); +console.log('Sorted without a compare function:', numericStringArray.sort()); +console.log('Sorted with compareNumbers:', numericStringArray.sort(compareNumbers)); + +console.log('mixedNumericArray:', mixedNumericArray.join()); +console.log('Sorted without a compare function:', mixedNumericArray.sort()); +console.log('Sorted with compareNumbers:', mixedNumericArray.sort(compareNumbers)); +</pre> + +<p>這個範例將產生下列結果。就如結果所示,當使用比較函式時,數字會被正確的排序,不管是數字還是數字字串。</p> + +<pre>stringArray: Blue,Humpback,Beluga +Sorted: Beluga,Blue,Humpback + +numberArray: 40,1,5,200 +Sorted without a compare function: 1,200,40,5 +Sorted with compareNumbers: 1,5,40,200 + +numericStringArray: 80,9,700 +Sorted without a compare function: 700,80,9 +Sorted with compareNumbers: 9,80,700 + +mixedNumericArray: 80,9,700,40,1,5,200 +Sorted without a compare function: 1,200,40,5,700,80,9 +Sorted with compareNumbers: 1,5,9,40,80,200,700 +</pre> + +<h3 id="Example:_Sorting_non-ASCII_characters" name="Example:_Sorting_non-ASCII_characters">排序非 ASCII 字元</h3> + +<p>為了排列非 ASCII 字元,即重音節字元(e、é、è、a、ä 等等),非英語字串:利用 {{jsxref("String.localeCompare")}}。此函式將比較這些字元,所以結果將會顯示正確的順序。</p> + +<pre class="brush: js">var items = ['réservé', 'premier', 'cliché', 'communiqué', 'café', 'adieu']; +items.sort(function (a, b) { + return a.localeCompare(b); +}); + +// items is ['adieu', 'café', 'cliché', 'communiqué', 'premier', 'réservé'] +</pre> + +<h3 id="Example:_Sorting_maps" name="Example:_Sorting_maps">排序 map</h3> + +<p><code>compareFunction</code> 可以被陣列中的各個元素多次呼叫。依據 <code>compareFunction</code> 的特性,這將會產生大量運算。越多元素要排序 <code>compareFunction</code> 就越多工作要做,因此選擇使用 <a href="/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Array/map">map</a> 來排列也就是一個更明智的選擇。作法為先迭代陣列一次來取得排序時所需的值至暫時的陣列,並對此臨時陣列進行排序。然後再迭代臨時陣列來將正確順序之值放入原始陣列中。</p> + +<pre class="brush: js" dir="rtl">// the array to be sorted +var list = ['Delta', 'alpha', 'CHARLIE', 'bravo']; + +// temporary array holds objects with position and sort-value +var mapped = list.map(function(el, i) { + return { index: i, value: el.toLowerCase() }; +}) + +// sorting the mapped array containing the reduced values +mapped.sort(function(a, b) { + if (a.value > b.value) { + return 1; + } + if (a.value < b.value) { + return -1; + } + return 0; +}); + +// container for the resulting order +var result = mapped.map(function(el){ + return list[el.index]; +}); +</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-15.4.4.11', 'Array.prototype.sort')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.sort', 'Array.prototype.sort')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.sort', 'Array.prototype.sort')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">瀏覽器相容性</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.sort")}}</p> +</div> + +<h2 id="See_also" name="See_also">參見</h2> + +<ul> + <li>{{jsxref("Array.prototype.reverse()")}}</li> + <li>{{jsxref("String.prototype.localeCompare()")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/splice/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/splice/index.html new file mode 100644 index 0000000000..2cb76617b8 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/splice/index.html @@ -0,0 +1,150 @@ +--- +title: Array.prototype.splice() +slug: Web/JavaScript/Reference/Global_Objects/Array/splice +tags: + - Array + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/splice +--- +<div>{{JSRef}}</div> + +<p><code><strong>splice()</strong></code> 方法可以藉由刪除既有元素並/或加入新元素來改變一個陣列的內容。</p> + +<div>{{EmbedInteractiveExample("pages/js/array-splice.html")}}</div> + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox"><var>array</var>.splice(<var>start[</var>, <var>deleteCount[</var>, <var>item1[</var>, <var>item2[</var>, <em>...]]]]</em>) +</pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>start</code></dt> + <dd>陣列中要開始改動的元素索引(起始為 0)。若索引大於陣列長度,則實際開始的索引值會被設為陣列長度。若索引為負,則會從陣列中最後一個元素開始往前改動(起始為 -1)且若其絕對值大於陣列的長度,則會被設為 0。</dd> + <dt><code>deleteCount</code> {{optional_inline}}</dt> + <dd>一個表示欲刪除的原陣列元素數量的整數。</dd> + <dd>若省略了 <code>deleteCount</code>,或假如其值大於 <code>array.length - start</code>(也就是 <code>deleteCount</code> 大於 <code>start</code> 算起的剩餘元素數量),則所有從 <code>start</code> 開始到陣列中最後一個元素都會被刪除。</dd> + <dd>若 <code>deleteCount</code> 為 0 或是負數,則不會有元素被刪除。 因此,你應該給定至少一個欲加入的新元素(見下方說明)。</dd> + <dt><code>item1, item2, <em>...</em></code> {{optional_inline}}</dt> + <dd>從 <code>start</code> 開始,要加入到陣列的元素。 如果你沒有指定任何元素,則 <code>splice()</code> 只會依照 <code>start</code> 和 <code>deleteCount</code> 刪除陣列的元素。</dd> +</dl> + +<h3 id="回傳值">回傳值</h3> + +<p>一個包含被刪除的元素陣列。如果只有一個元素被刪除,依舊是回傳包含一個元素的陣列。 倘若沒有元素被刪除,則會回傳空陣列。</p> + +<h2 id="說明">說明</h2> + +<p>如果你插入的元素數量和刪除的數量不同,則回傳的陣列長度也會和原先的不同。</p> + +<h2 id="範例">範例</h2> + +<h3 id="從索引_2_的位置開始,刪除_0_個元素並插入「drum」">從索引 2 的位置開始,刪除 0 個元素並插入「drum」</h3> + +<pre class="brush: js">var myFish = ['angel', 'clown', 'mandarin', 'sturgeon']; +var removed = myFish.splice(2, 0, 'drum'); + +// myFish 為 ["angel", "clown", "drum", "mandarin", "sturgeon"] +// removed 為 [], 沒有元素被刪除 +</pre> + +<h3 id="從索引_3_的位置開始,刪除_1_個元素">從索引 3 的位置開始,刪除 1 個元素</h3> + +<pre class="brush: js">var myFish = ['angel', 'clown', 'drum', 'mandarin', 'sturgeon']; +var removed = myFish.splice(3, 1); + +// removed 為 ["mandarin"] +// myFish 為 ["angel", "clown", "drum", "sturgeon"] +</pre> + +<h3 id="從索引_2_的位置開始,刪除_1_個元素並插入「trumpet」">從索引 2 的位置開始,刪除 1 個元素並插入「trumpet」</h3> + +<pre class="brush: js">var myFish = ['angel', 'clown', 'drum', 'sturgeon']; +var removed = myFish.splice(2, 1, 'trumpet'); + +// myFish 為 ["angel", "clown", "trumpet", "sturgeon"] +// removed 為 ["drum"]</pre> + +<h3 id="從索引_0_的位置開始,刪除_2_個元素並插入「parrot」、「anemone」和「blue」">從索引 0 的位置開始,刪除 2 個元素並插入「parrot」、「anemone」和「blue」</h3> + +<pre class="brush: js">var myFish = ['angel', 'clown', 'trumpet', 'sturgeon']; +var removed = myFish.splice(0, 2, 'parrot', 'anemone', 'blue'); + +// myFish 為 ["parrot", "anemone", "blue", "trumpet", "sturgeon"] +// removed 為 ["angel", "clown"]</pre> + +<h3 id="從索引_2_的位置開始,刪除_2_個元素">從索引 2 的位置開始,刪除 2 個元素</h3> + +<pre class="brush: js">var myFish = ['parrot', 'anemone', 'blue', 'trumpet', 'sturgeon']; +var removed = myFish.splice(myFish.length - 3, 2); + +// myFish 為 ["parrot", "anemone", "sturgeon"] +// removed 為 ["blue", "trumpet"]</pre> + +<h3 id="從索引_-2_的位置開始,刪除_1_個元素">從索引 -2 的位置開始,刪除 1 個元素</h3> + +<pre class="brush: js">var myFish = ['angel', 'clown', 'mandarin', 'sturgeon']; +var removed = myFish.splice(-2, 1); + +// myFish 為 ["angel", "clown", "sturgeon"] +// removed 為 ["mandarin"]</pre> + +<h3 id="從索引_2_的位置開始,刪除所有元素(含索引_2)">從索引 2 的位置開始,刪除所有元素(含索引 2)</h3> + +<pre class="brush: js">var myFish = ['angel', 'clown', 'mandarin', 'sturgeon']; +var removed = myFish.splice(2); + +// myFish 為 ["angel", "clown"] +// removed 為 ["mandarin", "sturgeon"]</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('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Initial definition. Implemented in JavaScript 1.2.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.12', 'Array.prototype.splice')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.splice', 'Array.prototype.splice')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.splice', 'Array.prototype.splice')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.splice")}}</p> +</div> + +<h2 id="參見">參見</h2> + +<ul> + <li>{{jsxref("Array.prototype.push()", "push()")}} / {{jsxref("Array.prototype.pop()", "pop()")}} — add/remove elements from the end of the array</li> + <li>{{jsxref("Array.prototype.unshift()", "unshift()")}} / {{jsxref("Array.prototype.shift()", "shift()")}} — add/remove elements from the beginning of the array</li> + <li>{{jsxref("Array.prototype.concat()", "concat()")}} — returns a new array comprised of this array joined with other array(s) and/or value(s)</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/unshift/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/unshift/index.html new file mode 100644 index 0000000000..7864ea6359 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/unshift/index.html @@ -0,0 +1,101 @@ +--- +title: Array.prototype.unshift() +slug: Web/JavaScript/Reference/Global_Objects/Array/unshift +tags: + - JavaScript + - Method + - Prototype + - Reference + - unshift + - 陣列 +translation_of: Web/JavaScript/Reference/Global_Objects/Array/unshift +--- +<div>{{JSRef}}</div> + +<p><code><strong>unshift()</strong></code> 方法會添加一個或多個元素至陣列的開頭,並且回傳陣列的新長度。</p> + +<div>{{EmbedInteractiveExample("pages/js/array-unshift.html")}}</div> + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox"><var>arr</var>.unshift(<var>element1</var>[, ...[, <var>elementN</var>]])</pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>element<em>N</em></code></dt> + <dd>欲添加至陣列開頭的元素。</dd> +</dl> + +<h3 id="回傳值">回傳值</h3> + +<p>呼叫此方法之物件的新 {{jsxref("Array.length", "length")}} 屬性值。</p> + +<h2 id="描述">描述</h2> + +<p><code>unshift</code> 方法會將一或多個給定值插入至一個類陣列(array-like)物件的開頭。</p> + +<p><code>unshift</code> 被刻意設計為具通用性;此方法可以藉由 {{jsxref("Function.call", "called", "", 1)}} 或 {{jsxref("Function.apply", "applied", "", 1)}} 應用於類似陣列的物件上。若欲應用此方法的物件不包含代表一系列啟始為零之數字屬性序列長度的 <code>length</code> 屬性,可能是不具任何意義的行為。</p> + +<h2 id="範例">範例</h2> + +<pre class="brush: js">var arr = [1, 2]; + +arr.unshift(0); // 執行後的結果是3,其代表處理後的陣列長度 +// arr is [0, 1, 2] + +arr.unshift(-2, -1); // = 5 +// arr is [-2, -1, 0, 1, 2] + +arr.unshift([-3]); +// arr is [[-3], -2, -1, 0, 1, 2] +</pre> + +<h2 id="規範">規範</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Initial definition. Implemented in JavaScript 1.2.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.13', 'Array.prototype.unshift')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.unshift', 'Array.prototype.unshift')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.unshift', 'Array.prototype.unshift')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.unshift")}}</p> +</div> + +<h2 id="參見">參見</h2> + +<ul> + <li>{{jsxref("Array.prototype.push()")}}</li> + <li>{{jsxref("Array.prototype.pop()")}}</li> + <li>{{jsxref("Array.prototype.shift()")}}</li> + <li>{{jsxref("Array.prototype.concat()")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/values/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/values/index.html new file mode 100644 index 0000000000..6f464a3d29 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/values/index.html @@ -0,0 +1,77 @@ +--- +title: Array.prototype.values() +slug: Web/JavaScript/Reference/Global_Objects/Array/values +translation_of: Web/JavaScript/Reference/Global_Objects/Array/values +--- +<div>{{JSRef}}</div> + +<p><strong><code>values()</code></strong> 方法會回傳一個包含陣列中的每一個索引之對應值(values)的新 <strong><code>Array Iterator</code></strong> 物件。</p> + +<pre class="brush: js">var a = ['w', 'y', 'k', 'o', 'p']; +var iterator = a.values(); + +console.log(iterator.next().value); // w +console.log(iterator.next().value); // y +console.log(iterator.next().value); // k +console.log(iterator.next().value); // o +console.log(iterator.next().value); // p</pre> + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox"><var>arr</var>.values()</pre> + +<h3 id="回傳值">回傳值</h3> + +<p>一個新的 {{jsxref("Array")}} 迭代器(iterator)物件。</p> + +<h2 id="範例">範例</h2> + +<h3 id="使用_for...of_迴圈進行迭代">使用 <code><a href="/zh-TW/docs/Web/JavaScript/Reference/Statements/for...of">for...of</a></code> 迴圈進行迭代</h3> + +<pre class="brush: js">var arr = ['w', 'y', 'k', 'o', 'p']; +var iterator = arr.values(); + +for (let letter of iterator) { + console.log(letter); +} +</pre> + +<h2 id="規範">規範</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-array.prototype.values', 'Array.prototype.values')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.values', 'Array.prototype.values')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.values")}}</p> +</div> + +<h2 id="參見">參見</h2> + +<ul> + <li>{{jsxref("Array.prototype.keys()")}}</li> + <li>{{jsxref("Array.prototype.entries()")}}</li> + <li>{{jsxref("Array.prototype.forEach()")}}</li> + <li>{{jsxref("Array.prototype.every()")}}</li> + <li>{{jsxref("Array.prototype.some()")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/arraybuffer/index.html b/files/zh-tw/web/javascript/reference/global_objects/arraybuffer/index.html new file mode 100644 index 0000000000..1fa59e5f0f --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/arraybuffer/index.html @@ -0,0 +1,225 @@ +--- +title: ArrayBuffer +slug: Web/JavaScript/Reference/Global_Objects/ArrayBuffer +translation_of: Web/JavaScript/Reference/Global_Objects/ArrayBuffer +--- +<p>{{JSRef}}</p> + +<p><strong><code>ArrayBuffer</code></strong> 物件是一種表示通用、固定大小的原始二進制資料緩衝。想要直接操作一個 <code>ArrayBuffer</code> 物件的內容是不可能的。若要讀寫該緩衝的內容則必須透過視圖,可以選擇建立一個 {{jsxref("DataView")}} 視圖物件或是一個限定其成員為某種型別的 {{jsxref("TypedArray")}} 視圖物件,它們皆能以特定的型別解讀、修改 <code>ArrayBuffer</code>。</p> + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox">new ArrayBuffer(length) +</pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>length</code></dt> + <dd>要建立的緩衝陣列大小,以位元組(byte)計算。</dd> +</dl> + +<h3 id="回傳值">回傳值</h3> + +<p>為一個新建立的指定大小 <code>ArrayBuffer</code> 物件,其內容皆初始化為 0。</p> + +<h3 id="Exceptions">Exceptions</h3> + +<p>A {{jsxref("RangeError")}} is thrown if the <code>length</code> is larger than {{jsxref("Number.MAX_SAFE_INTEGER")}} (>= 2 ** 53) or negative.</p> + +<h2 id="說明">說明</h2> + +<p>The <code>ArrayBuffer</code> constructor creates a new <code>ArrayBuffer</code> of the given length in bytes.</p> + +<h3 id="從既有的資料取得_ArrayBuffer">從既有的資料取得 ArrayBuffer</h3> + +<ul> + <li><a href="/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding#Appendix.3A_Decode_a_Base64_string_to_Uint8Array_or_ArrayBuffer">From a Base64 string</a></li> + <li><a href="/zh-TW/docs/Web/API/FileReader#readAsArrayBuffer()">從本地端檔案</a></li> +</ul> + +<h2 id="屬性">屬性</h2> + +<dl> + <dt><code>ArrayBuffer.length</code></dt> + <dd>The <code>ArrayBuffer</code> constructor's length property whose value is 1.</dd> + <dt>{{jsxref("ArrayBuffer.@@species", "get ArrayBuffer[@@species]")}}</dt> + <dd>The constructor function that is used to create derived objects.</dd> + <dt>{{jsxref("ArrayBuffer.prototype")}}</dt> + <dd>Allows the addition of properties to all <code>ArrayBuffer</code> objects.</dd> +</dl> + +<h2 id="方法">方法</h2> + +<dl> + <dt>{{jsxref("ArrayBuffer.isView", "ArrayBuffer.isView(arg)")}}</dt> + <dd>Returns <code>true</code> if <code>arg</code> is one of the ArrayBuffer views, such as <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray">typed array objects</a> or a {{jsxref("DataView")}}. Returns <code>false</code> otherwise.</dd> + <dt>{{jsxref("ArrayBuffer.transfer", "ArrayBuffer.transfer(oldBuffer [, newByteLength])")}} {{experimental_inline}}</dt> + <dd> + <div class="line" id="file-arraybuffer-transfer-LC6">Returns a new <code>ArrayBuffer</code> whose contents are taken from the <code>oldBuffer</code>'s data and then is either truncated or zero-extended by <code>newByteLength</code>.</div> + </dd> +</dl> + +<h2 id="ArrayBuffer_實例"><code>ArrayBuffer</code> 實例</h2> + +<p>所有的 <code>ArrayBuffer</code> 物件實例皆繼承自 {{jsxref("ArrayBuffer.prototype")}}.</p> + +<h3 id="屬性_2">屬性</h3> + +<p>{{page('zh-TW/Web/JavaScript/JavaScript_typed_arrays/ArrayBuffer/prototype','屬性')}}</p> + +<h3 id="方法_2">方法</h3> + +<p>{{page('/zh-TW/docs/Web/JavaScript/JavaScript_typed_arrays/ArrayBuffer/prototype','方法')}}</p> + +<dl> + <dt>{{jsxref("ArrayBuffer.slice()")}} {{non-standard_inline}}</dt> + <dd>Has the same functionality as {{jsxref("ArrayBuffer.prototype.slice()")}}.</dd> +</dl> + +<h2 id="範例">範例</h2> + +<p>In this example, we create a 8-byte buffer with a {{jsxref("Global_Objects/Int32Array", "Int32Array")}} view referring to the buffer:</p> + +<pre class="brush: js">var buffer = new ArrayBuffer(8); +var view = new Int32Array(buffer);</pre> + +<h2 id="規範">規範</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('Typed Array')}}</td> + <td>{{Spec2('Typed Array')}}</td> + <td>Superseded by ECMAScript 6.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-arraybuffer-constructor', 'ArrayBuffer')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition in an ECMA standard. Specified that <code>new</code> is required.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-arraybuffer-constructor', 'ArrayBuffer')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>7.0</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("2")}}</td> + <td>10</td> + <td>11.6</td> + <td>5.1</td> + </tr> + <tr> + <td><code>ArrayBuffer()</code> without <code>new</code> throws</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("44")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>ArrayBuffer.slice()</code> {{non-standard_inline}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}<br> + {{CompatNo}} {{CompatGeckoDesktop("53")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>4.0</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("2")}}</td> + <td>10</td> + <td>11.6</td> + <td>4.2</td> + </tr> + <tr> + <td><code>ArrayBuffer()</code> without <code>new</code> throws</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("44")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>ArrayBuffer.slice()</code> {{non-standard_inline}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}<br> + {{CompatNo}} {{CompatGeckoMobile("53")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="相容性備註">相容性備註</h2> + +<p>Starting with ECMAScript 2015, <code>ArrayBuffer</code> constructors require to be constructed with a {{jsxref("Operators/new", "new")}} operator. Calling an <code>ArrayBuffer</code> constructor as a function without <code>new</code>, will throw a {{jsxref("TypeError")}} from now on.</p> + +<pre class="brush: js example-bad">var dv = ArrayBuffer(10); +// TypeError: calling a builtin ArrayBuffer constructor +// without new is forbidden</pre> + +<pre class="brush: js example-good">var dv = new ArrayBuffer(10);</pre> + +<h2 id="參見">參見</h2> + +<ul> + <li>{{jsxref("TypedArray")}}</li> + <li>{{jsxref("SharedArrayBuffer")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/arraybuffer/prototype/index.html b/files/zh-tw/web/javascript/reference/global_objects/arraybuffer/prototype/index.html new file mode 100644 index 0000000000..8883a89cec --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/arraybuffer/prototype/index.html @@ -0,0 +1,110 @@ +--- +title: ArrayBuffer.prototype +slug: Web/JavaScript/Reference/Global_Objects/ArrayBuffer/prototype +translation_of: Web/JavaScript/Reference/Global_Objects/ArrayBuffer +--- +<div>{{JSRef}}</div> + +<p>The <strong><code>ArrayBuffer.prototype</code></strong> property represents the prototype for the {{jsxref("ArrayBuffer")}} object.</p> + +<div>{{js_property_attributes(0,0,0)}}</div> + +<h2 id="描述">描述</h2> + +<p><code>ArrayBuffer</code> instances inherit from <code>ArrayBuffer.prototype</code>. As with all constructors, you can change the constructor's prototype object to make changes to all <code>ArrayBuffer</code> instances.</p> + +<h2 id="屬性">屬性</h2> + +<dl> + <dt>ArrayBuffer.prototype.constructor</dt> + <dd>Specifies the function that creates an object's prototype. The initial value is the standard built-in <code>ArrayBuffer</code> constructor.</dd> + <dt>{{jsxref("ArrayBuffer.prototype.byteLength")}} {{readonlyInline}}</dt> + <dd>陣列大小,以位元組(byte)計算。此屬性在陣列建立之後就不可能改變了。<strong>唯讀</strong>。</dd> +</dl> + +<h2 id="方法">方法</h2> + +<dl> + <dt>{{jsxref("ArrayBuffer.prototype.slice()")}}</dt> + <dd>Returns a new <code>ArrayBuffer</code> whose contents are a copy of this <code>ArrayBuffer</code>'s bytes from <code>begin</code>, inclusive, up to <code>end</code>, exclusive. If either <code>begin</code> or <code>end</code> is negative, it refers to an index from the end of the array, as opposed to from the beginning.</dd> +</dl> + +<h2 id="規範">規範</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-arraybuffer.prototype', 'ArrayBuffer.prototype')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-arraybuffer.prototype', 'ArrayBuffer.prototype')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>7.0</td> + <td>{{ CompatGeckoDesktop("2")}}</td> + <td>10</td> + <td>11.6</td> + <td>5.1</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</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>Basic support</td> + <td>4.0</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("2")}}</td> + <td>10</td> + <td>11.6</td> + <td>4.2</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="參見">參見</h2> + +<ul> + <li>{{jsxref("ArrayBuffer")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/asyncfunction/index.html b/files/zh-tw/web/javascript/reference/global_objects/asyncfunction/index.html new file mode 100644 index 0000000000..c25f3ee3a1 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/asyncfunction/index.html @@ -0,0 +1,118 @@ +--- +title: AsyncFunction +slug: Web/JavaScript/Reference/Global_Objects/AsyncFunction +translation_of: Web/JavaScript/Reference/Global_Objects/AsyncFunction +--- +<div>{{JSRef}}</div> + +<p><code><strong>Async</strong></code><strong><code>Function</code> 建構子</strong>建立一個新的 {{jsxref("Statements/async_function", "async function")}} 物件。在 JavaScript 中,每一個非同步函數實際上是一個 <code>AsyncFunction</code> 物件。</p> + +<p>注意 <code>AsyncFunction</code> 不是一個全域物件。 它可以以下程式碼獲得。</p> + +<pre class="brush: js">Object.getPrototypeOf(async function(){}).constructor +</pre> + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox">new AsyncFunction([<var>arg1</var>[, <var>arg2</var>[, ...<var>argN</var>]],] <var>functionBody</var>)</pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>arg1, arg2, ... arg<em>N</em></code></dt> + <dd>Names to be used by the function as formal argument names. Each must be a string that corresponds to a valid JavaScript identifier or a list of such strings separated with a comma; for example "<code>x</code>", "<code>theValue</code>", or "<code>a,b</code>".</dd> + <dt><code>functionBody</code></dt> + <dd>一個字串。描述該函數定義的陳述式(statements)。</dd> +</dl> + +<h2 id="說明">說明</h2> + +<p>{{jsxref("Statements/async_function", "async function")}} objects created with the <code>AsyncFunction</code> constructor are parsed when the function is created. This is less efficient than declaring an async function with an {{jsxref("Statements/async_function", "async function expression")}} and calling it within your code, because such functions are parsed with the rest of the code.</p> + +<p>All arguments passed to the function are treated as the names of the identifiers of the parameters in the function to be created, in the order in which they are passed.</p> + +<div class="note"> +<p><strong>Note:</strong> {{jsxref("Statements/async_function", "async functions")}} created with the <code>AsyncFunction</code> constructor do not create closures to their creation contexts; they are always created in the global scope. When running them, they will only be able to access their own local variables and global ones, not the ones from the scope in which the <code>AsyncFunction</code> constructor was called. This is different from using {{jsxref("Global_Objects/eval", "eval")}} with code for an async function expression.</p> +</div> + +<p>以函數的方式執行 <code>AsyncFunction</code> 建構式 (不使用 <code>new</code> 運算子) 和以建構子的方式執行是等效的。</p> + +<h2 id="屬性">屬性</h2> + +<dl> + <dt><code><strong>AsyncFunction.length</strong></code></dt> + <dd><code>AsyncFuction</code> 建構子的長度為 1。</dd> + <dt>{{jsxref("AsyncFunction.prototype")}}</dt> + <dd>可加入屬性至所有陣列物件。</dd> +</dl> + +<h2 id="AsyncFunction_原型物件"><code>AsyncFunction</code> 原型物件</h2> + +<h3 id="屬性_2">屬性</h3> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncFunction/prototype', 'Properties')}}</div> + +<h2 id="AsyncFunction_實例"><code>AsyncFunction</code> 實例</h2> + +<p><code>AsyncFunction</code> 實例繼承 {{jsxref("AsyncFunction.prototype")}} 的屬性和方法. 和所有的建構子一樣,變更該建構子 (constructor) 的原型物件 (prototype object)將會影響所有的 <code>AsyncFunction</code> 實例。</p> + +<h2 id="範例">範例</h2> + +<h3 id="AsyncFunction_建構子建立一個非同步函數"> <code>AsyncFunction</code> 建構子建立一個非同步函數</h3> + +<pre class="brush: js">function resolveAfter2Seconds(x) { + return new Promise(resolve => { + setTimeout(() => { + resolve(x); + }, 2000); + }); +} + +var AsyncFunction = Object.getPrototypeOf(async function(){}).constructor + +var a = new AsyncFunction('a', + 'b', + 'return await resolveAfter2Seconds(a) + await resolveAfter2Seconds(b);'); + +a(10, 20).then(v => { + console.log(v); // prints 30 after 4 seconds +}); +</pre> + +<h2 id="規範">規範</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-async-function-objects', 'AsyncFunction object')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>Initial definition in ES2017.</td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<div> + + +<p>{{Compat("javascript.builtins.AsyncFunction")}}</p> +</div> + +<h2 id="參見">參見</h2> + +<ul> + <li>{{jsxref("Statements/async_function", "async function function")}}</li> + <li>{{jsxref("Operators/async_function", "async function expression")}}</li> + <li>{{jsxref("Global_Objects/Function", "Function")}}</li> + <li>{{jsxref("Statements/function", "function statement")}}</li> + <li>{{jsxref("Operators/function", "function expression")}}</li> + <li>{{jsxref("Functions_and_function_scope", "Functions and function scope", "", 1)}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/bigint/index.html b/files/zh-tw/web/javascript/reference/global_objects/bigint/index.html new file mode 100644 index 0000000000..705a85e255 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/bigint/index.html @@ -0,0 +1,279 @@ +--- +title: BigInt +slug: Web/JavaScript/Reference/Global_Objects/BigInt +translation_of: Web/JavaScript/Reference/Global_Objects/BigInt +--- +<p>{{JSRef}}{{SeeCompatTable}}</p> + +<p><code>BigInt</code> 是一個內建的物件,提供了表示大於2<sup>53</sup>的整數的功能 (2<sup>53</sup>是JavaScript原生的{{JSxRef("Number")}}能夠表示的最大值)</p> + +<h2 id="語法">語法</h2> + +<pre class="brush: js">BigInt(value); +</pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>value</code></dt> + <dd>欲創建的數值,可以為整數或字串。</dd> +</dl> + +<div class="blockIndicator note"> +<p><strong>Note</strong>: <code>BigInt()</code> 不和 {{JSxRef("Operators/new", "new")}} 一起使用。</p> +</div> + +<dl> +</dl> + +<h2 id="說明">說明</h2> + +<p><code>BigInt</code> 是透過在一個數值後加上 <code>n</code> ,例如 <code>10n</code> ,或呼叫 <code>BigInt()</code> 所生成的。</p> + +<pre class="brush: js">const theBiggestInt = 9007199254740991n; + +const alsoHuge = BigInt(9007199254740991); +// ↪ 9007199254740991n + +const hugeString = BigInt("9007199254740991"); +// ↪ 9007199254740991n + +const hugeHex = BigInt("0x1fffffffffffff"); +// ↪ 9007199254740991n + +const hugeBin = BigInt("0b11111111111111111111111111111111111111111111111111111"); +// ↪ 9007199254740991n +</pre> + +<p><code>BigInt</code> 跟 {{JSxRef("Number")}} 很像,但在某些部分有些許不同 — 它不可以被用在內建的 {{JSxRef("Math")}} 物件方法中、而且不可以跟 <code>Number</code> 的實體混用運算子。</p> + +<div class="blockIndicator warning"> +<p>{{JSxRef("Number")}} 和 <code>BigInt</code> 不能混和計算 — 他們必須被轉換到同一個型態。</p> + +<p>然而,在相互轉換時要注意, <code>BigInt</code> 在被轉換成 <code>Number</code> 時可能會遺失部分精度的資訊。</p> +</div> + +<h3 id="類別資訊">類別資訊</h3> + +<p>當使用 <code>typeof</code> 測試時,一個 <code>BigInt</code> 會回傳 "bigint":</p> + +<pre class="brush: js">typeof 1n === 'bigint'; // true +typeof BigInt('1') === 'bigint'; // true +</pre> + +<p>當使用 <code>Object</code> 來包裹時,<code>BigInt</code> 會被看成是普通的 "object" 型態:</p> + +<pre class="brush: js">typeof Object(1n) === 'object'; // true +</pre> + +<h3 id="Operators">Operators</h3> + +<p>下列的運算子可以被用在 <code>BigInt</code> 上 (或由object包裹的 <code>BigInt</code>): <code>+</code>, <code>*</code>, <code>-</code>, <code>**</code>, <code>%</code>.</p> + +<pre class="brush: js">const previousMaxSafe = BigInt(Number.MAX_SAFE_INTEGER); +// ↪ 9007199254740991 + +const maxPlusOne = previousMaxSafe + 1n; +// ↪ 9007199254740992n + +const theFuture = previousMaxSafe + 2n; +// ↪ 9007199254740993n, this works now! + +const multi = previousMaxSafe * 2n; +// ↪ 18014398509481982n + +const subtr = multi – 10n; +// ↪ 18014398509481972n + +const mod = multi % 10n; +// ↪ 2n + +const bigN = 2n ** 54n; +// ↪ 18014398509481984n + +bigN * -1n +// ↪ –18014398509481984n +</pre> + +<p><code>/</code> 運算子也同樣的能夠運行。然而,因為型態是 <code>BigInt</code> 而不是 <code>BigDecimal</code> ,除法運算會無條件捨去小數。也就是說,回傳值不會包含小數部分。</p> + +<div class="blockIndicator warning"> +<p>回傳值帶小數的運算在使用<code>BigInt</code> 時小數部分會被捨去。</p> +</div> + +<pre class="brush: js">const expected = 4n / 2n; +// ↪ 2n + +const rounded = 5n / 2n; +// ↪ 2n, not 2.5n + +</pre> + +<h3 id="比較">比較</h3> + +<p>一個 <code>BigInt</code> 並不嚴格等於一個 {{JSxRef("Global_Objects/Number", "Number")}},但他們會一般相等。</p> + +<pre class="brush: js">0n === 0 +// ↪ false + +0n == 0 +// ↪ true</pre> + +<p>一個 {{JSxRef("Global_Objects/Number", "Number")}} 和 <code>BigInt</code> 可以像普通運算一樣比較。</p> + +<pre class="brush: js">1n < 2 +// ↪ true + +2n > 1 +// ↪ true + +2 > 2 +// ↪ false + +2n > 2 +// ↪ false + +2n >= 2 +// ↪ true</pre> + +<p>他們可以參雜在陣列中並照預期的被排序。</p> + +<pre class="brush: js">const mixed = [4n, 6, -12n, 10, 4, 0, 0n]; +// ↪ [4n, 6, -12n, 10, 4, 0, 0n] + +mixed.sort(); +// ↪ [-12n, 0, 0n, 10, 4n, 4, 6] +</pre> + +<p>Note that comparisons with <code>Object</code>-wrapped <code>BigInt</code>s act as with other objects, only indicating equality when the same object instance is compared:</p> + +<pre class="brush: js">0n === Object(0n); // false +Object(0n) === Object(0n); // false + +const o = Object(0n); +o === o // true +</pre> + +<h3 id="Conditionals">Conditionals</h3> + +<p>A <code>BigInt</code> behaves like a {{JSxRef("Global_Objects/Number", "Number")}} in cases where it is converted to a {{JSxRef("Global_Objects/Boolean", "Boolean")}}: via the {{JSxRef("Global_Objects/Boolean", "Boolean")}} function; when used with logical operators {{JSxRef("Operators/Logical_Operators", "Logical Operators")}} <code>||</code>, <code>&&</code>, and <code>!</code>; or within a conditional test like an {{JSxRef("Statements/if...else", "if statement")}}.</p> + +<pre class="brush: js">if (0n) { + console.log('Hello from the if!'); +} else { + console.log('Hello from the else!'); +} + +// ↪ "Hello from the else!" + +0n || 12n +// ↪ 12n + +0n && 12n +// ↪ 0n + +Boolean(0n) +// ↪ false + +Boolean(12n) +// ↪ true + +!12n +// ↪ false + +!0n +// ↪ true +</pre> + +<h2 id="方法">方法</h2> + +<dl> + <dt>{{JSxRef("BigInt.asIntN()")}}</dt> + <dd>Wraps a BigInt between -2<sup>width-1</sup> and 2<sup>width-1</sup>-1</dd> + <dt>{{JSxRef("BigInt.asUintN()")}}</dt> + <dd>Wraps a BigInt between 0 and 2<sup>width</sup>-1</dd> +</dl> + +<h2 id="屬性">屬性</h2> + +<dl> + <dt>{{JSxRef("BigInt.prototype")}}</dt> + <dd>允許對一個 <code>BigInt</code> 物件增加其屬性。</dd> +</dl> + +<h2 id="BigInt_物件實體"><code>BigInt</code> 物件實體</h2> + +<p>All <code>BigInt</code> instances inherit from <code>BigInt.prototype</code>. The prototype object of the <code>BigInt</code> constructor can be modified to affect all <code>BigInt</code> instances.</p> + +<h3 id="方法_2">方法</h3> + +<p>{{page("/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt/prototype", "Methods")}}</p> + +<h2 id="建議用法">建議用法</h2> + +<h3 id="轉型">轉型</h3> + +<p>因為在 {{JSxRef("Global_Objects/Number", "Number")}} 和 <code>BigInt</code> 之間轉換可能造成精度遺失,建議當數值會超過2<sup>53</sup>時只使用 <code>BigInt</code> ,而不要在兩者之間進行轉換。</p> + +<h3 id="加密">加密</h3> + +<p><code>BigInt</code> 支援的運算並非常數時間。因此 <code>BigInt</code> <a href="https://www.chosenplaintext.ca/articles/beginners-guide-constant-time-cryptography.html">不適用在加密學上</a>。</p> + +<h2 id="範例">範例</h2> + +<h3 id="計算質數">計算質數</h3> + +<pre class="brush: js">function isPrime(p) { + for (let i = 2n; i * i <= p; i++) { + if (p % i === 0n) return false; + } + return true; +} + +// Takes a BigInt as an argument and returns a BigInt +function nthPrime(nth) { + let maybePrime = 2n; + let prime = 0n; + + while (nth >= 0n) { + if (isPrime(maybePrime)) { + nth -= 1n; + prime = maybePrime; + } + maybePrime += 1n; + } + + return prime; +} + +nthPrime(20n) +// ↪ 73n</pre> + +<h2 id="規範">規範</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">規範</th> + <th scope="col">狀態</th> + </tr> + <tr> + <td><a href="https://tc39.github.io/proposal-bigint/#sec-bigint-objects">BigInt</a></td> + <td>Stage 3</td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<div> + + +<p>{{Compat("javascript.builtins.BigInt")}}</p> +</div> + +<h2 id="另見">另見</h2> + +<ul> + <li>{{JSxRef("Number")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/boolean/index.html b/files/zh-tw/web/javascript/reference/global_objects/boolean/index.html new file mode 100644 index 0000000000..6c8d690b15 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/boolean/index.html @@ -0,0 +1,199 @@ +--- +title: Boolean +slug: Web/JavaScript/Reference/Global_Objects/Boolean +translation_of: Web/JavaScript/Reference/Global_Objects/Boolean +--- +<div>{{JSRef}}</div> + +<p><strong><code>Boolean</code></strong> 是布林值的包覆器。</p> + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox">new Boolean([<var>value</var>])</pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>value</code> {{optional_inline}}</dt> + <dd>這個<code>Boolean</code>物件的初始值。</dd> +</dl> + +<h2 id="說明">說明</h2> + +<p>傳入的第一個參數值,如果需要的話,會被轉換成布林值。如果沒傳值,或者是<code>0</code>、<code>-0</code>、{{jsxref("null")}}、<code>false</code>、{{jsxref("NaN")}}、{{jsxref("undefined")}}、空字串(<code>""</code>)的話,這個物件的值會被初始化成<code>false</code>。大多數情況下,DOM 物件 {{domxref("document.all")}} 被傳入後,也會將其初始化為<code>false</code>。至於其他的值,包含所有物件或<code>"false"</code>字串,都會使其初始化為<code>true</code>。</p> + +<p>不要將原始型別的布林值和這個布林物件搞混,它們並不相同。</p> + +<p>在判斷式中,任何物件只要不是 {{jsxref("undefined")}} 或 {{jsxref("null")}} ,儘管是值為<code>false</code> 的 <code>Boolean</code> 物件,都會被轉換成<code>true</code>。舉例來說,下列的 {{jsxref("Statements/if...else", "if")}} 判斷式中的布林值即為<code>true</code>:</p> + +<pre class="brush: js">var x = new Boolean(false); +if (x) { + // this code is executed +} +</pre> + +<p>以上這個行為和<code>Boolean</code>原始型別沒有關連,反倒是下面的 {{jsxref("Statements/if...else", "if")}} 判斷式會正確地將其視為<code>false</code>:</p> + +<pre class="brush: js">var x = false; +if (x) { + // this code is not executed +} +</pre> + +<p>不要用<code>Boolean</code>物件將非布林值轉換成布林值。反而要將<code>Boolean</code>視為函式去轉換非布林值:</p> + +<pre class="brush: js">var x = Boolean(expression); // 較好 +var x = new Boolean(expression); // 不要用 +</pre> + +<p>如果你要指定任何物件,包括值為<code>false</code>的<code>Boolean</code>物件,作為<code>Boolean</code>物件的初始值,則該<code>Boolean</code>物件的值依舊為<code>true</code>。</p> + +<pre class="brush: js">var myFalse = new Boolean(false); // 初始值給false,實際上為true +var g = new Boolean(myFalse); // 想當然耳,true +var myString = new String('Hello'); // 字串物件,'Hello' +var s = new Boolean(myString); // 依舊為true +</pre> + +<p>不要使用<code>Boolean</code>物件代替<code>Boolean</code>的原始型別!</p> + +<h2 id="屬性">屬性</h2> + +<dl> + <dt><code>Boolean.length</code></dt> + <dd>長度永遠為1。</dd> + <dt>{{jsxref("Boolean.prototype")}}</dt> + <dd>原型為<code>Boolean</code>的建構式。</dd> +</dl> + +<h2 id="方法">方法</h2> + +<p>全域的<code>Boolean</code>物件自身沒有任何方法,它只有從原型鏈繼承而來的方法。</p> + +<h2 id="Boolean_實體"><code>Boolean</code> 實體</h2> + +<p>所有 <code>Boolean</code> 實體會繼承 {{jsxref("Boolean.prototype")}} 。和所有建構式一樣,原型物件會指派給實體那些繼承的屬性和方法。</p> + +<h3 id="屬性_2">屬性</h3> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean/prototype', 'Properties')}}</div> + +<h3 id="方法_2">方法</h3> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean/prototype', 'Methods')}}</div> + +<h2 id="範例">範例</h2> + +<h3 id="用_false_作為初始值建立_Boolean_物件">用 <code>false</code> 作為初始值建立 <code>Boolean</code> 物件</h3> + +<pre class="brush: js">var bNoParam = new Boolean(); +var bZero = new Boolean(0); +var bNull = new Boolean(null); +var bEmptyString = new Boolean(''); +var bfalse = new Boolean(false); +</pre> + +<h3 id="用_true_作為初始值建立_Boolean_物件">用 <code>true</code> 作為初始值建立 <code>Boolean</code> 物件</h3> + +<pre class="brush: js">var btrue = new Boolean(true); +var btrueString = new Boolean('true'); +var bfalseString = new Boolean('false'); +var bSuLin = new Boolean('Su Lin'); +var bArrayProto = new Boolean([]); +var bObjProto = new Boolean({}); +</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('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.6', 'Boolean')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-boolean-objects', 'Boolean')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-boolean-objects', 'Boolean')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatIE("6.0")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</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>{{jsxref("Boolean.prototype")}}</li> + <li>{{Glossary("Boolean")}}</li> + <li><a href="http://en.wikipedia.org/wiki/Boolean_data_type">Boolean data type (Wikipedia)</a></li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/dataview/index.html b/files/zh-tw/web/javascript/reference/global_objects/dataview/index.html new file mode 100644 index 0000000000..d7cf6d6ed4 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/dataview/index.html @@ -0,0 +1,173 @@ +--- +title: DataView +slug: Web/JavaScript/Reference/Global_Objects/DataView +translation_of: Web/JavaScript/Reference/Global_Objects/DataView +--- +<div>{{JSRef}}</div> + +<p><strong><code>DataView</code></strong> 視圖提供了一個底層介面來讀寫 {{jsxref("ArrayBuffer")}} 中的二進位資料。<code>DataView</code> 能用多種不同的型別對 <code>ArrayBuffer</code> 進行修改、解讀,且可自訂資料的位元組順序而不受系統平台限制。<code>DataView</code> 物件僅為視圖,並不會存放資料,所有的資料皆實際儲存於 <code>ArrayBuffer</code> 物件當中。</p> + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox">new DataView(buffer [, byteOffset [, byteLength]])</pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>buffer</code></dt> + <dd>要給DataView物件操作的資料容器並且不能為null</dd> + <dt><code>byteOffset</code> {{optional_inline}}</dt> + <dd>The offset, in bytes, to the first byte in the specified buffer for the new view to reference. If not specified, the view of the buffer will start with the first byte.</dd> + <dt><code>byteLength</code> {{optional_inline}}</dt> + <dd>The number of elements in the byte array. If unspecified, length of the view will match the buffer's length.</dd> +</dl> + +<h3 id="回傳值">回傳值</h3> + +<p>A new <code>DataView</code> object representing the specified data buffer.</p> + +<h3 id="Errors_thrown">Errors thrown</h3> + +<dl> + <dt><code>{{jsxref("RangeError")}}</code></dt> + <dd>Thrown if the <code>byteOffset</code> and <code>byteLength</code> result in the specified view extending past the end of the buffer.</dd> +</dl> + +<h2 id="描述">描述</h2> + +<h3 id="位元組順序">位元組順序</h3> + +<p>Multi-byte number formats are represented in memory differently depending on machine architecture, see {{Glossary("Endianness")}} for an explanation. DataView accessors provide explicit control of how data will be accessed irrespective of the platform architecture's endianness.</p> + +<pre class="brush: js">var littleEndian = (function() { + var buffer = new ArrayBuffer(2); + new DataView(buffer).setInt16(0, 256, true /* littleEndian */); + // Int16Array uses the platform's endianness. + return new Int16Array(buffer)[0] === 256; +})(); +console.log(littleEndian); // true or false +</pre> + +<h2 id="屬性">屬性</h2> + +<dl> + <dt>DataView.length</dt> + <dd>The <code>DataView</code> constructor's length property whose value is 3.</dd> + <dt>{{jsxref("DataView.prototype")}}</dt> + <dd>Allows the addition of properties to all <code>DataView</code> objects.</dd> +</dl> + +<h2 id="DataView_實例"><code>DataView</code> 實例</h2> + +<p>All <code>DataView</code> instances inherit from {{jsxref("DataView.prototype")}}.</p> + +<h3 id="屬性_2">屬性</h3> + +<p>{{page('en-US/Web/JavaScript/Reference/Global_Objects/DataView/prototype','Properties')}}</p> + +<h3 id="方法">方法</h3> + +<p>{{page('en-US/Web/JavaScript/Reference/Global_Objects/DataView/prototype','Methods')}}</p> + +<h2 id="範例">範例</h2> + +<pre class="brush: js">var buffer = new ArrayBuffer(16); +var dv = new DataView(buffer, 0); + +dv.setInt16(1, 42); +dv.getInt16(1); //42 +</pre> + +<h2 id="規範">規範</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('Typed Array')}}</td> + <td>{{Spec2('Typed Array')}}</td> + <td>Superseded by ECMAScript 6</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-dataview-constructor', 'DataView')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition in an ECMA standard</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-dataview-constructor', 'DataView')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>9.0</td> + <td>{{CompatGeckoDesktop("15.0")}}</td> + <td>10</td> + <td>12.1</td> + <td>5.1</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</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>Basic support</td> + <td>4.0</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("15")}}</td> + <td>{{CompatUnknown}}</td> + <td>12.0</td> + <td>4.2</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Firefox-specific_notes">Firefox-specific notes</h2> + +<p>Starting with Gecko / SpiderMonkey 40 {{geckoRelease(40)}}, <code>DataView</code> requires to be constructed with a {{jsxref("Operators/new", "new")}} operator. Calling <code>DataView()</code> as a function without <code>new</code>, will throw a {{jsxref("TypeError")}} from now on.</p> + +<pre class="brush: js example-bad">var dv = DataView(buffer, 0); +// TypeError: calling a builtin DataView constructor without new is forbidden</pre> + +<pre class="brush: js example-good">var dv = new DataView(buffer, 0);</pre> + +<h2 id="參見">參見</h2> + +<ul> + <li><a class="link-https" href="https://github.com/jDataView/jDataView">jDataView</a>: JavaScript library that polyfills and extends the <code>DataView</code> API to all browsers and Node.js.</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/date/getday/index.html b/files/zh-tw/web/javascript/reference/global_objects/date/getday/index.html new file mode 100644 index 0000000000..abdc0e89a1 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/date/getday/index.html @@ -0,0 +1,72 @@ +--- +title: Date.prototype.getDay() +slug: Web/JavaScript/Reference/Global_Objects/Date/getDay +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getDay +--- +<div>{{JSRef}}</div> + +<p><span class="seoSummary"><strong><code>getDay()</code></strong> 方法會根據當地時間將指定日期返回一星期中的第幾天,</span>其中0代表星期日。 在當月的某天可以參考{{jsxref("Date.prototype.getDate()")}}。</p> + +<div>{{EmbedInteractiveExample("pages/js/date-getday.html", "shorter")}}</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"><code><var>dateObj</var>.getDay()</code></pre> + +<h3 id="返回值">返回值</h3> + +<p>返回一個整數,數值介於0到6之間,取決於當地時間對應出指定日期為星期幾:0代表星期日,1代表星期一,2代表星期二,依此類推。</p> + +<h2 id="範例">範例</h2> + +<h3 id="使用_getDay">使用 <code>getDay()</code></h3> + +<p>下面第二行表示根據日期對象'Xmas95'的值,把1賦值給'weekday'。則1995年12月25日是星期一。</p> + +<pre class="brush: js notranslate">var Xmas95 = new Date('December 25, 1995 23:15:30'); +var weekday = Xmas95.getDay(); + +console.log(weekday); // 1 +</pre> + +<div class="blockIndicator note"> +<p><strong>Note:</strong> 如果需要,可以使用{{jsxref("DateTimeFormat", "Intl.DateTimeFormat")}}加上<code>options</code>參數來獲取星期幾全名。使使用此方法能輕鬆做出各種國際語言:</p> + +<pre class="brush: js notranslate">var options = { weekday: 'long'}; +console.log(new Intl.DateTimeFormat('en-US', options).format(Xmas95)); +// Monday +console.log(new Intl.DateTimeFormat('de-DE', options).format(Xmas95)); +// Montag +</pre> +</div> + +<h2 id="規範">規範</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-date.prototype.getday', 'Date.prototype.getDay')}}</td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器兼容性">瀏覽器兼容性</h2> + + + +<p>{{Compat("javascript.builtins.Date.getDay")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Date.prototype.getUTCDate()")}}</li> + <li>{{jsxref("Date.prototype.getUTCDay()")}}</li> + <li>{{jsxref("Date.prototype.setDate()")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/date/index.html b/files/zh-tw/web/javascript/reference/global_objects/date/index.html new file mode 100644 index 0000000000..91c0305aa4 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/date/index.html @@ -0,0 +1,263 @@ +--- +title: Date +slug: Web/JavaScript/Reference/Global_Objects/Date +tags: + - Date + - JavaScript +translation_of: Web/JavaScript/Reference/Global_Objects/Date +--- +<div>{{JSRef}}</div> + +<p>建立一個 JavaScript <strong><code>Date</code></strong> 物件來指向某一個時間點。Date 物件是基於世界標準時間(UTC) 1970 年 1 月 1 日開始的毫秒數值來儲存時間。</p> + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox">new Date(); +new Date(<var>value</var>); +new Date(<var>dateString</var>); +new Date(<var>year</var>, <var>month</var>[, <var>day</var>[, <var>hour</var>[, <var>minutes</var>[, <var>seconds</var>[, <var>milliseconds</var>]]]]]); +</pre> + +<div class="note"> +<p><strong>附註:</strong> JavaScript <code>Date</code> 物件只能由以 Date 作為建構子來產生,如果把 Date 作為一般的函數來呼叫(省略掉 {{jsxref("Operators/new", "new")}} 運算子)將會得到一個字串而非 Date 物件;與其它 JavaScript 物件不同,它並沒有物件實體語法(例如:以中刮號 [ ] 表示陣列的宣告方式)。</p> +</div> + +<h3 id="參數">參數</h3> + +<div class="note"> +<p><strong>附註:</strong>當傳入超過一個參數到 Date 建構子,若參數值超過它的合理範圍(例如:傳數值 13 到月份,或傳數值 70 給分鐘),相鄰的參數值將會被調整。例如: <code>new Date(2013, 13, 1)</code> 將等同於 <code>new Date(2014, 1, 1)</code> 都會建立代表 <code>2014-02-01</code> 的物件(注意月份值由 0 開始)。同樣的, <code>new Date(2013, 2, 1, 0, 70)</code> 與 <code>new Date(2013, 2, 1, 1, 10)</code> 一樣會建立代表 <code>2013-03-01T01:10:00</code> 的 Date 物件。</p> +</div> + +<div class="note"> +<p><strong>附註:</strong>當傳入超過一個參數到 Date 建構子,所指定的參數值會視為本地時間。如果希望指定的值為世界標準時間(UTC),則應使用 <code>new Date({{jsxref("Date.UTC()", "Date.UTC(...)")}})</code> 語法,傳入一樣格式的參數。</p> +</div> + +<dl> + <dt><code>value</code></dt> + <dd>自世界標準時間(UTC) 1970 年 1 月 1 日 00:00:00 開始的毫秒整數(Integer)值(Unix 紀元;但要注意到大多 Unix 時間<span class="short_text" id="result_box" lang="zh-CN"><span>戳記是以秒而非毫秒為單位)。</span></span></dd> + <dt><code>dateString</code></dt> + <dd>表示時間日期的字串。這個字串應該要能被 {{jsxref("Date.parse()")}} 方法解析(符合 <a href="http://tools.ietf.org/html/rfc2822#page-14">IETF-compliant RFC 2822 timestamps</a> 及 <a href="http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.15">version of ISO8601</a> 格式要求). + <div class="note"> + <p><strong>附註:</strong> 由於各家瀏覽器有所不同且具有差異性,因此非常不鼓勵使用 Date 建構子(或 <code>Date.parse</code> 方法,它們是同等的)來解析時間日期字串。</p> + </div> + </dd> + <dt><code>year</code></dt> + <dd>表示年份的整數。當數值落在 0 到 99 之間,表示 1900 到 1999 之間的年份。參考{{anch("Two_digit_years_map_to_1900_-_1999", "下面的範例")}}.</dd> + <dt><code>month</code></dt> + <dd>表示月份的整數。由 0 開始(一月)到 11 (十二月)。</dd> + <dt><code>day</code></dt> + <dd>選用。表示月份中第幾天的整數值。</dd> + <dt><code>hour</code></dt> + <dd>選用。表示小時數的整數值。</dd> + <dt><code>minute</code></dt> + <dd>選用。表示分鐘數的整數值。</dd> + <dt><code>second</code></dt> + <dd>選用。表示秒數的整數值。</dd> + <dt><code>millisecond</code></dt> + <dd>選用。表示毫秒數的整數值。</dd> +</dl> + +<h2 id="描述">描述</h2> + +<ul> + <li>如果沒有傳入任務參數到建構子,會依系統設定建立出代表當下時間的 Date 物件。</li> + <li>如果傳入至少兩個參數,缺少日期的話會設為 1,其它參數則會被設定為 0。</li> + <li>JavaScript 的 date 基於世界標準時間(UTC)1970 年 1 月 1 日午夜的毫秒數。一天有 86,400,000 毫秒。JavaScript <code>Date</code> 物件可表示的範圍由世界標準時間(UTC) 1970 年 1 月 1 日為基準的 -100,000,000 天到 100,000,000 天。</li> + <li>JavaScript <code>Date</code> 物件提供跨平台一致的行為。這個時間數值可以在系統之間傳遞表示相同的時間,如果建立本地的時間物件,其表現將會與本地習慣相對應。</li> + <li>JavaScript <code>Date</code> 物件提供了若干 UTC (通用的) 以及本地時間方法。UTC,也被稱為格林威治標準時間(GMT)被指定作為世界時間的標準。本地時間指的是被設定在執行 JavaScript 電腦上的時間。</li> + <li>以函數方式呼叫 <code>Date</code> (也就是省略 {{jsxref("Operators/new", "new")}} 建構子)將會回傳一個表示當下時間日期的字串。</li> +</ul> + +<h2 id="屬性">屬性</h2> + +<dl> + <dt>{{jsxref("Date.prototype")}}</dt> + <dd>允許填加屬於到 JavaScript <code>Date</code> 物件。</dd> + <dt><code>Date.length</code></dt> + <dd><code>Date.length</code> 的值為 7。這是建構子能夠處理的參數數量。</dd> +</dl> + +<h2 id="方法">方法</h2> + +<dl> + <dt>{{jsxref("Date.now()")}}</dt> + <dd>回傳對應於當下時間的數值 - 1970/01/01 00:00:00 (UTC) 到當下的毫秒數。</dd> + <dt>{{jsxref("Date.parse()")}}</dt> + <dd>解析字串所表示的時間,回傳由 1970/01/01 00:00:00 (UTC) 到該時間的毫秒數值。 + <div class="note"> + <p><strong>附註:</strong>由於瀏覽器之間的不同與差異,強烈不建議使用 <code>Date.parse</code> 。</p> + </div> + </dd> + <dt>{{jsxref("Date.UTC()")}}</dt> + <dd>需要傳入與建構子相同的參數數目(即 2 到 7 個),會得到由 1970-01-01 00:00:00 UTC 到該日期時間的毫秒數。(輸入的參數會視為世界標準時間,而非本地時間)</dd> +</dl> + +<h2 id="JavaScript_Date_物件實體">JavaScript <code>Date</code> 物件實體</h2> + +<p>所有 <code>Date</code> 物件實體繼承自 {{jsxref("Date.prototype")}} 。這個 Date 建構子的 prototype 物件可以被修改以影響所有 Date 物件實體。</p> + +<h3 id="Date.prototype_方法">Date.prototype 方法</h3> + +<div>{{page('/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Date/prototype', '方法')}}</div> + +<h2 id="範例">範例</h2> + +<h3 id="幾種建立_Date_物件的方式">幾種建立 Date 物件的方式</h3> + +<p>接下來的幾個範例,展示幾種建立 Date 物件的方式:</p> + +<div class="note"> +<p><strong>附註:</strong> 由於瀏覽器之間的不同與差異,強烈不建議使用解析字串的方式建立 Date 物件。</p> +</div> + +<pre class="brush: js">var today = new Date(); +var birthday = new Date('December 17, 1995 03:24:00'); +var birthday = new Date('1995-12-17T03:24:00'); +var birthday = new Date(1995, 11, 17); +var birthday = new Date(1995, 11, 17, 3, 24, 0); +</pre> + +<h3 id="兩位數的年份對應到_1900_-_1999">兩位數的年份對應到 1900 - 1999</h3> + +<p>為了建立及取得西元 0 到 99 的日期,應該使用 {{jsxref("Date.prototype.setFullYear()")}} 以及 {{jsxref("Date.prototype.getFullYear()")}} 方法。</p> + +<pre class="brush: js">var date = new Date(98, 1); // Sun Feb 01 1998 00:00:00 GMT+0000 (GMT) + +// 過時的方法,98 在這裡對應到 1998 年 +date.setYear(98); // Sun Feb 01 1998 00:00:00 GMT+0000 (GMT) + +date.setFullYear(98); // Sat Feb 01 0098 00:00:00 GMT+0000 (BST) +</pre> + +<h3 id="計算執行時間">計算執行時間</h3> + +<p>下面的例子展示如何使用兩個 Date 物件來求得執行程式所花費毫秒數。</p> + +<p>由於日(在夏令時轉換時)、月及年的長度並非固定,如果表示經過時間採用時、分、秒以外的單位,需要對這些差異作深入的研究,以處理可能發生的問題。</p> + +<pre class="brush: js">// 使用 Date 物件 +var start = Date.now(); + +// 要計算執行時間的程式放在這裡 +doSomethingForALongTime(); +var end = Date.now(); +var elapsed = end - start; // 執行程式經過的毫秒數 +</pre> + +<pre class="brush: js">// 使用內建方法 +var start = new Date(); + +// 要計算執行時間的程式放在這裡 +doSomethingForALongTime(); +var end = new Date(); +var elapsed = end.getTime() - start.getTime(); // 執行程式經過的毫秒數 +</pre> + +<pre class="brush: js">// 測試一個函數執行時間,並返回其回傳值 +function printElapsedTime(fTest) { + var nStartTime = Date.now(), + vReturn = fTest(), + nEndTime = Date.now(); + + console.log('Elapsed time: ' + String(nEndTime - nStartTime) + ' milliseconds'); + return vReturn; +} + +yourFunctionReturn = printElapsedTime(yourFunction); +</pre> + +<div class="note"> +<p><strong>附註:</strong>在瀏覽器支援 {{domxref("window.performance", "Web Performance API", "", 1)}} 高精度特性下, {{domxref("Performance.now()")}} 可以提供比 {{jsxref("Date.now()")}} 更可靠、精確的執行時間測試結果。</p> +</div> + +<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-date-objects', 'Date')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-date-objects', 'Date')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.9', 'Date')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>初步定義。實作在 JavaScript 1.1。</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>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td> + <p>基本支援</p> + </td> + <td>{{CompatVersionUnknown}} [1]</td> + <td>{{CompatVersionUnknown}} [1]</td> + <td>{{CompatVersionUnknown}} [2]</td> + <td>{{CompatVersionUnknown}} [1]</td> + <td>{{CompatVersionUnknown}} [1]</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> + <p>基本支援</p> + </td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] 一些瀏覽器在解析日期時間會發生問題: <a href="http://dygraphs.com/date-formats.html">3/14/2012 blog from danvk Comparing FF/IE/Chrome on Parsing Date Strings</a></p> + +<p>[2] <a href="https://msdn.microsoft.com/en-us//library/ie/ff743760(v=vs.94).aspx">ISO8601 Date Format is not supported</a> in Internet Explorer 8, and other version can have <a href="http://dygraphs.com/date-formats.html">issues when parsing dates</a></p> diff --git a/files/zh-tw/web/javascript/reference/global_objects/date/now/index.html b/files/zh-tw/web/javascript/reference/global_objects/date/now/index.html new file mode 100644 index 0000000000..00b4842f0f --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/date/now/index.html @@ -0,0 +1,123 @@ +--- +title: Date.now() +slug: Web/JavaScript/Reference/Global_Objects/Date/now +tags: + - Date + - JavaScript + - 參考 + - 方法 + - 方法補完 +translation_of: Web/JavaScript/Reference/Global_Objects/Date/now +--- +<div>{{JSRef}}</div> + +<p><strong><code>Date.now()</code></strong> 方法回傳自 1970/01/01 00:00:00 UTC 起經過的毫秒數。</p> + +<h2 id="格式">格式</h2> + +<pre class="syntaxbox"><code>var timeInMs = Date.now();</code></pre> + +<h3 id="回傳值">回傳值</h3> + +<p>一個代表由經 UNIX 紀元起經過的毫秒數值({{jsxref("Number")}})。</p> + +<h2 id="描述">描述</h2> + +<p>由於 <code>now()</code> 是 {{jsxref("Date")}} 的靜態方法,你只能用 <code>Date.now()</code> 的方式呼叫它。</p> + +<h2 id="補完">補完</h2> + +<p>這個函數是 ECMA-262 第 5 版的標準。 對於未更新支援此方法的引擎,可以利用底下的程式補上:</p> + +<pre class="brush: js">if (!Date.now) { + Date.now = function now() { + return new Date().getTime(); + }; +} +</pre> + +<h2 id="規範">規範</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">規範</th> + <th scope="col">狀態</th> + <th scope="col">註</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.9.4.4', 'Date.now')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>初始定義,實作在 JavaScript 1.5 。</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-date.now', 'Date.now')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-date.now', 'Date.now')}}</td> + <td>{{Spec2('ESDraft')}}</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>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>基本支援</td> + <td>{{CompatChrome("5")}}</td> + <td>{{CompatGeckoDesktop("1.9")}}</td> + <td>{{CompatIE("9")}}</td> + <td>{{CompatOpera("10.50")}}</td> + <td>{{CompatSafari("4")}}</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>{{domxref("Performance.now()")}} — 提供亞毫秒級的時間戳記,作為評估網頁效能的解決方案。</li> + <li>{{domxref("console.time()")}} / {{domxref("console.timeEnd()")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/date/prototype/index.html b/files/zh-tw/web/javascript/reference/global_objects/date/prototype/index.html new file mode 100644 index 0000000000..edd6a3fb47 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/date/prototype/index.html @@ -0,0 +1,245 @@ +--- +title: Date.prototype +slug: Web/JavaScript/Reference/Global_Objects/Date/prototype +tags: + - Date + - JavaScript + - 原型 + - 參考資料 + - 屬性 +translation_of: Web/JavaScript/Reference/Global_Objects/Date +--- +<div>{{JSRef}}</div> + +<p><strong><code>Date.prototype</code></strong> 屬性表示 {{jsxref("Date")}} 建構子的原型。</p> + +<div>{{js_property_attributes(0, 0, 1)}}</div> + +<h2 id="描述">描述</h2> + +<p>JavaScript {{jsxref("Date")}} 實體繼承自 <code>Date.prototype。你可以藉由改變建構子的原型物件,來影響所有繼承自</code> JavaScript {{jsxref("Date")}} 的實體。</p> + +<p>為了千年年份(換個說法,考慮現在已到了 2000 年)的相容性,設定上你應該採用完整的年份。舉例來說,使用 1998 而不是 98 。為了讓你能取得完整的年份資料, Javascript 包含了 {{jsxref("Date.prototype.getFullYear()", "getFullYear()")}} , {{jsxref("Date.prototype.setFullYear()", "setFullYear()")}} , {{jsxref("Date.prototype.getUTCFullYear()", "getUTCFullYear()")}} 以及 {{jsxref("Date.prototype.setUTCFullYear()", "setUTCFullYear()")}} 方法。</p> + +<p>自 ECMAScript 6 開始, <code>Date.prototype</code> 物件只是個一般物件,而不是一個 {{jsxref("Date")}} 實體。</p> + +<h2 id="屬性">屬性</h2> + +<dl> + <dt><code>Date.prototype.constructor</code></dt> + <dd>回傳一個能建立實體的函數,這是 {{jsxref("Date")}} 預設的建構子。</dd> +</dl> + +<h2 id="方法">方法</h2> + +<h3 id="Getter">Getter</h3> + +<dl> + <dt>{{jsxref("Date.prototype.getDate()")}}</dt> + <dd>回傳本地時間月份中的日期(1-31)。</dd> + <dt>{{jsxref("Date.prototype.getDay()")}}</dt> + <dd>回傳本地時間星期中的日子(0-6)。</dd> + <dt>{{jsxref("Date.prototype.getFullYear()")}}</dt> + <dd>回傳本地時間的年份( 以 4 位數表現)。</dd> + <dt>{{jsxref("Date.prototype.getHours()")}}</dt> + <dd>回傳本地時間的小時(0-23)。</dd> + <dt>{{jsxref("Date.prototype.getMilliseconds()")}}</dt> + <dd>回傳本地時間的毫秒數(0-999)。</dd> + <dt>{{jsxref("Date.prototype.getMinutes()")}}</dt> + <dd>回傳本地時間的分鐘數(0-59)。</dd> + <dt>{{jsxref("Date.prototype.getMonth()")}}</dt> + <dd>回傳本地時間的月份(0-11)。</dd> + <dt>{{jsxref("Date.prototype.getSeconds()")}}</dt> + <dd>回傳本地時間的秒數(0-59)。</dd> + <dt>{{jsxref("Date.prototype.getTime()")}}</dt> + <dd>回傳由 1970-01-01 00:00:00 UTC 開始,到代表時間經過的毫秒數(以負值表示 1970 年之前的時間)。</dd> + <dt>{{jsxref("Date.prototype.getTimezoneOffset()")}}</dt> + <dd>回傳本地時差為多少分鐘。</dd> + <dt>{{jsxref("Date.prototype.getUTCDate()")}}</dt> + <dd>回傳標準時間的在月份中的日期(1-31)。</dd> + <dt>{{jsxref("Date.prototype.getUTCDay()")}}</dt> + <dd>回傳標準時間在星期中的日子(0-6)。</dd> + <dt>{{jsxref("Date.prototype.getUTCFullYear()")}}</dt> + <dd>回傳標準時間的年份( 以 4 位數表現)。</dd> + <dt>{{jsxref("Date.prototype.getUTCHours()")}}</dt> + <dd>回傳標準時間的小時數(0-23)。</dd> + <dt>{{jsxref("Date.prototype.getUTCMilliseconds()")}}</dt> + <dd>回傳標準時間裡的毫秒數(0-999)。</dd> + <dt>{{jsxref("Date.prototype.getUTCMinutes()")}}</dt> + <dd>回傳標準時間的分鐘數(0-59)。</dd> + <dt>{{jsxref("Date.prototype.getUTCMonth()")}}</dt> + <dd>回傳標準時間的月份數(0-11)。</dd> + <dt>{{jsxref("Date.prototype.getUTCSeconds()")}}</dt> + <dd>回傳標準時間的秒數(0-59)。</dd> + <dt>{{jsxref("Date.prototype.getYear()")}} {{deprecated_inline}}</dt> + <dd>回本地時間的年份(通常 2-3 位數)。用 {{jsxref("Date.prototype.getFullYear()", "getFullYear()")}} 取代。</dd> +</dl> + +<h3 id="Setter">Setter</h3> + +<dl> + <dt>{{jsxref("Date.prototype.setDate()")}}</dt> + <dd>設定本地時間月份中的日期。</dd> + <dt>{{jsxref("Date.prototype.setFullYear()")}}</dt> + <dd>設定本地時間的完整年份(以 4 位數表達 4 位數年份)。</dd> + <dt>{{jsxref("Date.prototype.setHours()")}}</dt> + <dd>設定本地時間的小時數。</dd> + <dt>{{jsxref("Date.prototype.setMilliseconds()")}}</dt> + <dd>設定本地時間的毫秒數。</dd> + <dt>{{jsxref("Date.prototype.setMinutes()")}}</dt> + <dd>設定本地時間的分鐘數。</dd> + <dt>{{jsxref("Date.prototype.setMonth()")}}</dt> + <dd>設定本地時間的月份。</dd> + <dt>{{jsxref("Date.prototype.setSeconds()")}}</dt> + <dd>設定本地時間的秒數。</dd> + <dt>{{jsxref("Date.prototype.setTime()")}}</dt> + <dd>設定這個 {{jsxref("Date")}} 物件距 1970-01-01 00:00:00 UTC 的毫秒數,允許使用負值表示之前的時間。</dd> + <dt>{{jsxref("Date.prototype.setUTCDate()")}}</dt> + <dd>設定標準時間月份中的日期。</dd> + <dt>{{jsxref("Date.prototype.setUTCFullYear()")}}</dt> + <dd>設定標準時間的完整年份(以 4 位數表示 4 位數年分)。</dd> + <dt>{{jsxref("Date.prototype.setUTCHours()")}}</dt> + <dd>設定標準時間的小時數。</dd> + <dt>{{jsxref("Date.prototype.setUTCMilliseconds()")}}</dt> + <dd>設定標準時間的毫秒數。</dd> + <dt>{{jsxref("Date.prototype.setUTCMinutes()")}}</dt> + <dd>設定標準時間的分鐘數。</dd> + <dt>{{jsxref("Date.prototype.setUTCMonth()")}}</dt> + <dd>設定標準時間的月份數。</dd> + <dt>{{jsxref("Date.prototype.setUTCSeconds()")}}</dt> + <dd>設定標準時間的秒數。</dd> + <dt>{{jsxref("Date.prototype.setYear()")}} {{deprecated_inline}}</dt> + <dd>設定本地時間的年份(使用 2-3 位數)。使用 {{jsxref("Date.prototype.setFullYear()", "setFullYear()")}} 取代。</dd> +</dl> + +<h3 id="Conversion_getter">Conversion getter</h3> + +<dl> + <dt>{{jsxref("Date.prototype.toDateString()")}}</dt> + <dd>以可閱讀的字串型式,回傳 {{jsxref("Date")}} 的部分資訊。</dd> + <dt>{{jsxref("Date.prototype.toISOString()")}}</dt> + <dd>將日期時間轉換成 ISO 8601 格式的字串回傳。</dd> + <dt>{{jsxref("Date.prototype.toJSON()")}}</dt> + <dd>回傳等義於 {{jsxref("Date")}} 物件使用 {{jsxref("Date.prototype.toISOString()", "toISOString()")}} 方法的結果。特別使用 {{jsxref("JSON.stringify()")}} 處理。</dd> + <dt>{{jsxref("Date.prototype.toGMTString()")}} {{deprecated_inline}}</dt> + <dd>回傳 {{jsxref("Date")}} 以 GMT (UT) 時區基準代表的時間字串。使用 {{jsxref("Date.prototype.toUTCString()", "toUTCString()")}} 方法來取代。</dd> + <dt>{{jsxref("Date.prototype.toLocaleDateString()")}}</dt> + <dd>依照系統的時間地區設定,回傳日期字串。</dd> + <dt>{{jsxref("Date.prototype.toLocaleFormat()")}} {{non-standard_inline}}</dt> + <dd>傳入格式化字串參數,將日期時間轉換成指定格式的字串。</dd> + <dt>{{jsxref("Date.prototype.toLocaleString()")}}</dt> + <dd>回傳依系統的地區設定導出的日期時間字串。覆寫自 {{jsxref("Object.prototype.toLocaleString()")}} 方法。</dd> + <dt>{{jsxref("Date.prototype.toLocaleTimeString()")}}</dt> + <dd>回傳依系統的地區設定導出的時間字串。</dd> + <dt>{{jsxref("Date.prototype.toSource()")}} {{non-standard_inline}}</dt> + <dd>回傳一個建立相同 {{jsxref("Date")}} 物件的程式碼字串;你可以拿這個結果來建立新物件。覆寫自 {{jsxref("Object.prototype.toSource()")}} 方法。</dd> + <dt>{{jsxref("Date.prototype.toString()")}}</dt> + <dd>回傳代表此 {{jsxref("Date")}} 物件的字串。覆寫自 {{jsxref("Object.prototype.toString()")}} 方法。</dd> + <dt>{{jsxref("Date.prototype.toTimeString()")}}</dt> + <dd>以人類可讀的格式,回傳時間部分的字串。</dd> + <dt>{{jsxref("Date.prototype.toUTCString()")}}</dt> + <dd>依 UTC 時區,轉換出時間日期字串。</dd> + <dt>{{jsxref("Date.prototype.valueOf()")}}</dt> + <dd>回傳 {{jsxref("Date")}} 物件的原始數值。覆寫自 {{jsxref("Object.prototype.valueOf()")}} 方法。</dd> +</dl> + +<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('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>初步定義。實作在 JavaScript 1.1.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.9.5', 'Date.prototype')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-properties-of-the-date-prototype-object', 'Date.prototype')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-properties-of-the-date-prototype-object', 'Date.prototype')}}</td> + <td>{{Spec2('ESDraft')}}</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>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> + <tr> + <td>一般物件</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("41")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</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> + <tr> + <td>一般物件</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("41")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> diff --git a/files/zh-tw/web/javascript/reference/global_objects/date/utc/index.html b/files/zh-tw/web/javascript/reference/global_objects/date/utc/index.html new file mode 100644 index 0000000000..60f1c555f0 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/date/utc/index.html @@ -0,0 +1,157 @@ +--- +title: Date.UTC() +slug: Web/JavaScript/Reference/Global_Objects/Date/UTC +tags: + - Date + - JavaScript + - 參考 + - 方法 +translation_of: Web/JavaScript/Reference/Global_Objects/Date/UTC +--- +<div>{{JSRef}}</div> + +<p><strong><code>Date.UTC()</code></strong> 方法接受與建構子相同長度的參數,將參數視為通用時間(UTC)來計算回傳由 1970-01-01 00:00:00 UTC 所經過的毫秒數。</p> + +<h2 id="格式">格式</h2> + +<pre class="syntaxbox"><code>Date.UTC(<var>year</var>, <var>month</var>[, <var>day</var>[, <var>hour</var>[, <var>minute</var>[, <var>second</var>[, <var>millisecond</var>]]]]])</code></pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>year</code></dt> + <dd>1900 年後的年份。</dd> + <dt><code>month</code></dt> + <dd>月份,介於 0 到 11 之間。</dd> + <dt><code>day</code></dt> + <dd>選用。月份中的日期,介於 1 到 31 之間。</dd> + <dt><code>hour</code></dt> + <dd>選用。小時,介於 0 到 23 之間。</dd> + <dt><code>minute</code></dt> + <dd>選用。分鐘數,介於 0 到 59 之間。</dd> + <dt><code>second</code></dt> + <dd>選用。秒數,介於 0 到 59 之間。</dd> + <dt><code>millisecond</code></dt> + <dd>選用。毫秒數 0 到 999 之間。</dd> +</dl> + +<h3 id="回傳值">回傳值</h3> + +<p>得到傳入這個 {{jsxref("Date")}} 方法的參數所代表時間,與 1970-01-01 00:00:00 UTC 相差的毫秒數。</p> + +<h2 id="描述">描述</h2> + +<p><code>UTC()</code> 取得以逗號分隔的時間參數,回傳 1970-01-01 00:00:00 UTC 與該時間相差的毫秒數。</p> + +<p>你應該指定完成的年份資料,例如: 1998。如果一個 0 到 99 的年份被指定,這個方法會將它轉換為 20 世紀的年份(變為 19xx 年),例如你傳入 95 ,則會被當作 1995 年被指定。</p> + +<p>這個 <code>UTC()</code> 方法與 {{jsxref("Date")}} 建構子有兩個地方不同。</p> + +<ul> + <li><code>Date.UTC()</code> 使用 UTC 時區而不是當地時區。</li> + <li><code>Date.UTC()</code> 回傳一個數值而不是 {{jsxref("Date")}} 物件。</li> +</ul> + +<p>當你指定參數超出預期的範圍, UTC( ) 方法會去調整其它的參數使之成立。比如如果你指定月份為 15 ,年份將被加 1 ,以 3 作為傳入的月份。</p> + +<p>因為 UTC( ) 是 {{jsxref("Date")}} 的一個靜態方法,只能使用 <code>Date.UTC() 的方式呼叫,而不能由建立出來的 </code>{{jsxref("Date")}} 物件去執行它。</p> + +<h2 id="範例">範例</h2> + +<h3 id="使用_Date.UTC()">使用 <code>Date.UTC()</code></h3> + +<p>以下利用它來將指定的時間以 UTC 而非本地時間的方式來建立 {{jsxref("Date")}} 物件:</p> + +<pre class="brush:js">var utcDate = new Date(Date.UTC(96, 11, 1, 0, 0, 0)); +</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-date.utc', 'Date.UTC')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-date.utc', 'Date.UTC')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.9.4.3', 'Date.UTC')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>初始定義。<br> + 實作在 JavaScript 1.0.</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>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>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="相關資源">相關資源</h2> + +<ul> + <li>{{jsxref("Date.parse()")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/error/columnnumber/index.html b/files/zh-tw/web/javascript/reference/global_objects/error/columnnumber/index.html new file mode 100644 index 0000000000..1db87220e8 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/error/columnnumber/index.html @@ -0,0 +1,81 @@ +--- +title: Error.prototype.columnNumber +slug: Web/JavaScript/Reference/Global_Objects/Error/columnNumber +translation_of: Web/JavaScript/Reference/Global_Objects/Error/columnNumber +--- +<div>{{JSRef}} {{non-standard_header}}</div> + +<p>「行數」屬性含括了檔案中引起錯誤的所在行數。</p> + +<h2 id="範例">範例</h2> + +<h3 id="使用_columnNumber">使用 <code>columnNumber</code></h3> + +<pre class="brush: js">var e = new Error('Could not parse input'); +throw e; +console.log(e.columnNumber) // 0 +</pre> + +<h2 id="規格">規格</h2> + +<p>不是任何規格的一部份,尚未標準化。</p> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</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>Basic support</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Error.prototype.stack")}} {{non-standard_inline}}</li> + <li>{{jsxref("Error.prototype.lineNumber")}} {{non-standard_inline}}</li> + <li>{{jsxref("Error.prototype.fileName")}} {{non-standard_inline}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/error/index.html b/files/zh-tw/web/javascript/reference/global_objects/error/index.html new file mode 100644 index 0000000000..623a5dfeac --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/error/index.html @@ -0,0 +1,233 @@ +--- +title: Error +slug: Web/JavaScript/Reference/Global_Objects/Error +tags: + - Error + - JavaScript + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/Error +--- +<div>{{JSRef}}</div> + +<p><strong><code>Error</code></strong> 建構函式能用來建立一個 error 物件。當執行期間發生錯誤時,<code>Error</code> 物件實體會被拋出。<code>Error</code> 物件也可作為自訂例外的基礎物件,請參考下方的標準內建錯誤類型。</p> + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox">new Error([<var>message</var>[, <var>fileName</var>[, <var>lineNumber</var>]]])</pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>message</code> {{optional_inline}}</dt> + <dd>人們可閱讀的錯誤說明。</dd> + <dt><code>fileName</code> {{optional_inline}} {{non-standard_inline}}</dt> + <dd>The value for the <code>fileName</code> property on the created <code>Error</code> object. Defaults to the name of the file containing the code that called the <code>Error()</code> constructor.</dd> + <dt><code>lineNumber</code> {{optional_inline}} {{non-standard_inline}}</dt> + <dd>Optional. The value for the <code>lineNumber</code> property on the created <code>Error</code> object. Defaults to the line number containing the <code>Error()</code> constructor invocation.</dd> +</dl> + +<h2 id="描述">描述</h2> + +<p>Runtime errors result in new <code>Error</code> objects being created and thrown.</p> + +<p>This page documents the use of the <code>Error</code> object itself and its use as a constructor function. For a list of properties and methods inherited by <code>Error</code> instances, see {{jsxref("Error.prototype")}}.</p> + +<h3 id="錯誤類型">錯誤類型</h3> + +<p>Besides the generic <code>Error</code> constructor, there are six other core error constructors in JavaScript. For client-side exceptions, see <a href="/en-US/docs/Web/JavaScript/Guide/Statements#Exception_Handling_Statements">Exception Handling Statements</a>.</p> + +<dl> + <dt>{{jsxref("EvalError")}}</dt> + <dd>Creates an instance representing an error that occurs regarding the global function {{jsxref("Global_Objects/eval", "eval()")}}.</dd> + <dt>{{jsxref("InternalError")}} {{non-standard_inline}}</dt> + <dd>Creates an instance representing an error that occurs when an internal error in the JavaScript engine is thrown. E.g. "too much recursion".</dd> + <dt>{{jsxref("RangeError")}}</dt> + <dd>Creates an instance representing an error that occurs when a numeric variable or parameter is outside of its valid range.</dd> + <dt>{{jsxref("ReferenceError")}}</dt> + <dd>Creates an instance representing an error that occurs when de-referencing an invalid reference.</dd> + <dt>{{jsxref("SyntaxError")}}</dt> + <dd>Creates an instance representing a syntax error that occurs while parsing code in {{jsxref("Global_Objects/eval", "eval()")}}.</dd> + <dt>{{jsxref("TypeError")}}</dt> + <dd>Creates an instance representing an error that occurs when a variable or parameter is not of a valid type.</dd> + <dt>{{jsxref("URIError")}}</dt> + <dd>Creates an instance representing an error that occurs when {{jsxref("Global_Objects/encodeURI", "encodeURI()")}} or {{jsxref("Global_Objects/decodeURI", "decodeURI()")}} are passed invalid parameters.</dd> +</dl> + +<h2 id="屬性">屬性</h2> + +<dl> + <dt>{{jsxref("Error.prototype")}}</dt> + <dd>Allows the addition of properties to <code>Error</code> instances.</dd> +</dl> + +<h2 id="方法">方法</h2> + +<p>The global <code>Error</code> object contains no methods of its own, however, it does inherit some methods through the prototype chain.</p> + +<h2 id="Error_實體"><code>Error</code> 實體</h2> + +<div>{{page('en-US/docs/JavaScript/Reference/Global_Objects/Error/prototype', 'Description')}}</div> + +<h3 id="屬性_2">屬性</h3> + +<div>{{page('en-US/docs/JavaScript/Reference/Global_Objects/Error/prototype', 'Properties')}}</div> + +<h3 id="方法_2">方法</h3> + +<div>{{page('en-US/docs/JavaScript/Reference/Global_Objects/Error/prototype', 'Methods')}}</div> + +<h2 id="範例">範例</h2> + +<h3 id="Throwing_a_generic_error">Throwing a generic error</h3> + +<p>Usually you create an <code>Error</code> object with the intention of raising it using the {{jsxref("Statements/throw", "throw")}} keyword. You can handle the error using the {{jsxref("Statements/try...catch", "try...catch")}} construct:</p> + +<pre class="brush: js">try { + throw new Error('Whoops!'); +} catch (e) { + console.log(e.name + ': ' + e.message); +} +</pre> + +<h3 id="Handling_a_specific_error">Handling a specific error</h3> + +<p>You can choose to handle only specific error types by testing the error type with the error's {{jsxref("Object.prototype.constructor", "constructor")}} property or, if you're writing for modern JavaScript engines, {{jsxref("Operators/instanceof", "instanceof")}} keyword:</p> + +<pre class="brush: js">try { + foo.bar(); +} catch (e) { + if (e instanceof EvalError) { + console.log(e.name + ': ' + e.message); + } else if (e instanceof RangeError) { + console.log(e.name + ': ' + e.message); + } + // ... etc +} +</pre> + +<h3 id="Custom_Error_Types">Custom Error Types</h3> + +<p>You might want to define your own error types deriving from <code>Error</code> to be able to <code>throw new MyError()</code> and use <code>instanceof MyError</code> to check the kind of error in the exception handler. The common way to do this is demonstrated below.</p> + +<div class="warning"> +<p>Note that the thrown <code>MyError</code> will report incorrect <code>lineNumber</code> and <code>fileName</code> at least in Firefox.</p> +</div> + +<p>See also the <a href="http://stackoverflow.com/questions/1382107/whats-a-good-way-to-extend-error-in-javascript">"What's a good way to extend Error in JavaScript?" discussion on Stackoverflow</a>.</p> + +<pre class="brush: js">// Create a new object, that prototypically inherits from the Error constructor +function MyError(message) { + this.name = 'MyError'; + this.message = message || 'Default Message'; + this.stack = (new Error()).stack; +} +MyError.prototype = Object.create(Error.prototype); +MyError.prototype.constructor = MyError; + +try { + throw new MyError(); +} catch (e) { + console.log(e.name); // 'MyError' + console.log(e.message); // 'Default Message' +} + +try { + throw new MyError('custom message'); +} catch (e) { + console.log(e.name); // 'MyError' + console.log(e.message); // 'custom message' +}</pre> + +<h2 id="規範">規範</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.1.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.11', 'Error')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-error-objects', 'Error')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-error-objects', 'Error')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</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>Feature</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>Basic support</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>{{jsxref("Error.prototype")}}</li> + <li>{{jsxref("Statements/throw", "throw")}}</li> + <li>{{jsxref("Statements/try...catch", "try...catch")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/function/apply/index.html b/files/zh-tw/web/javascript/reference/global_objects/function/apply/index.html new file mode 100644 index 0000000000..698d2f46fc --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/function/apply/index.html @@ -0,0 +1,260 @@ +--- +title: Function.prototype.apply() +slug: Web/JavaScript/Reference/Global_Objects/Function/apply +translation_of: Web/JavaScript/Reference/Global_Objects/Function/apply +--- +<div>{{JSRef}}</div> + +<p><code><strong>apply() </strong>方法會呼叫一個以 this 的代表值和一個陣列形式的值組(或是一個 </code><a href="/en-US/docs/Web/JavaScript/Guide/Indexed_collections#Working_with_array-like_objects">array-like object</a> <code>)為參數的函式。</code></p> + +<div class="note"> +<p><strong>注意:</strong>這個函式的語法和{{jsxref("Function.call", "call()")}} 幾乎一樣,最大的不同是 <code>call()</code> 接受<code><strong>一連串的參數</strong></code>,而 <code>apply() 接受<strong>一組陣列形式的參數</strong>。</code></p> +</div> + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox"><var>fun</var>.apply(<var>thisArg, </var>[<var>argsArray</var>])</pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>thisArg</code></dt> + <dd>讓 <em><code>fun </code></em><code>呼叫時</code>可以視為 this 的值。注意,這可能並不是最後會在方法裡看見的值:如果這是一個在非 {{jsxref("Strict_mode", "non-strict mode", "", 1)}} 下運作的程式碼,{{jsxref("null")}} 及 {{jsxref("undefined")}} 將會被全域物件取代,而原始類別將被封裝。</dd> + <dt><code>argsArray</code></dt> + <dd>一個 array-like object ,定義了 <em><code>fun </code></em><code>要呼叫的一組參數,如果沒有需要提供,可以傳入 </code>{{jsxref("null")}} 或 {{jsxref("undefined")}} 。從 ECMAScript 5 開始,這些參數不僅可以是泛型的 array-like object ,而不一定要是一組陣列。查看下方的{{anch("Browser_compatibility", "browser compatibility")}} 資訊。</dd> +</dl> + +<h3 id="回傳值">回傳值</h3> + +<p>傳入 <code><strong>this </strong>值及一組參數後得到的結果。</code></p> + +<h2 id="描述">描述</h2> + +<p>在呼叫一個現存的函式時,你可以傳入不同的 <code>this 物件值。this 參考到現在的物件,也就是正在執行的物件。apply 讓你可以只寫一次方法後,讓其他物件也繼承到這個方法,而不用一再重寫。</code></p> + +<p><code>apply 與</code> {{jsxref("Function.call", "call()")}} 非常相似,不同的是支援的傳入參數類型。使用陣列形式的參數,而不是命名過的接收參數。使用 <code>apply 時,</code>你可以選擇使用陣列實字:<code><em>fun</em>.apply(this, ['eat', 'bananas']); 或是 </code>{{jsxref("Array")}} 物件: <code><em>fun</em>.apply(this, new Array('eat', 'bananas'))。</code></p> + +<p><code>除此之外,你也可以使用</code> {{jsxref("Functions/arguments", "arguments")}} 代表 <code>argsArray 參數。arguments 是在函式裡的區域變數,可用來存取所有沒有特別被所呼叫物件指定的傳入參數。因此,使用 apply 時你不需要知道所呼叫函式的指定參數。使用 </code>arguments 把所有參數傳入呼叫的方法裡,而被呼叫的方法會接手處理這些參數。</p> + +<p>從 ECMAScript 5th 版本後,也可以使用陣列形式的物件,在實踐上這代表他會擁有 <code>length 以及整數範圍 </code> <code>(0...length-1) 的屬性。舉例來說,你可以使用 </code>{{domxref("NodeList")}} 或是一個像這樣的自定義屬性: <code>{ 'length': 2, '0': 'eat', '1': 'bananas' }。</code></p> + +<div class="note"> +<p>一般瀏覽器,包括 Chrome 14 及 Internet Explorer 9,仍不支援陣列形式的物件,所以會對此丟出一個錯誤。</p> +</div> + +<h2 id="範例">範例</h2> + +<h3 id="使用_apply_與建構子鏈結">使用 <code>apply</code> 與建構子鏈結</h3> + +<p>您可以使用 <code>apply</code> 鏈結 {{jsxref("Operators/new", "constructors", "", 1)}} 一個物件,與 Java 相似,如下範例中我們可以建立一個全域的 {{jsxref("Function")}} 方法叫 <code>construct</code>,使您可以使用類陣列的物件與建構子去替代參數列表。</p> + +<pre class="brush: js">Function.prototype.construct = function(aArgs) { + var oNew = Object.create(this.prototype); + this.apply(oNew, aArgs); + return oNew; +}; +</pre> + +<div class="note"> +<p><strong>注意:</strong>如上範例的 <code>Object.create()</code> 方法是屬於比較新的寫法。如需使用閉包的替代方法,請參考以下的範例:</p> + +<pre class="brush: js">Function.prototype.construct = function(aArgs) { + var fConstructor = this, fNewConstr = function() { + fConstructor.apply(this, aArgs); + }; + fNewConstr.prototype = fConstructor.prototype; + return new fNewConstr(); +};</pre> +</div> + +<p>使用範例:</p> + +<pre class="brush: js">function MyConstructor() { + for (var nProp = 0; nProp < arguments.length; nProp++) { + this['property' + nProp] = arguments[nProp]; + } +} + +var myArray = [4, 'Hello world!', false]; +var myInstance = MyConstructor.construct(myArray); + +console.log(myInstance.property1); // logs 'Hello world!' +console.log(myInstance instanceof MyConstructor); // logs 'true' +console.log(myInstance.constructor); // logs 'MyConstructor' +</pre> + +<div class="note"> +<p><strong>注意:</strong>This non-native <code>Function.construct</code> method will not work with some native constructors (like {{jsxref("Date")}}, for example). In these cases you have to use the {{jsxref("Function.prototype.bind")}} method (for example, imagine having an array like the following, to be used with {{jsxref("Global_Objects/Date", "Date")}} constructor: <code>[2012, 11, 4]</code>; in this case you have to write something like: <code>new (Function.prototype.bind.apply(Date, [null].concat([2012, 11, 4])))()</code> — anyhow this is not the best way to do things and probably should not be used in any production environment).</p> +</div> + +<h3 id="使用_apply_於內建的函數">使用 <code>apply</code> 於內建的函數</h3> + +<p>apply 可以巧妙的在某些任務中使用內建函數,否則可能會循環遍歷整個陣列來寫入。如下範例,我們使用 <code>Math.max/Math.min</code> 來找出陣列中最大/最小的值。</p> + +<pre class="brush: js">// min/max number in an array +var numbers = [5, 6, 2, 3, 7]; + +// using Math.min/Math.max apply +var max = Math.max.apply(null, numbers); +// This about equal to Math.max(numbers[0], ...) +// or Math.max(5, 6, ...) + +var min = Math.min.apply(null, numbers); + +// vs. simple loop based algorithm +max = -Infinity, min = +Infinity; + +for (var i = 0; i < numbers.length; i++) { + if (numbers[i] > max) { + max = numbers[i]; + } + if (numbers[i] < min) { + min = numbers[i]; + } +} +</pre> + +<p>But beware: in using <code>apply</code> this way, you run the risk of exceeding the JavaScript engine's argument length limit. The consequences of applying a function with too many arguments (think more than tens of thousands of arguments) vary across engines (JavaScriptCore has hard-coded <a class="link-https" href="https://bugs.webkit.org/show_bug.cgi?id=80797">argument limit of 65536</a>), because the limit (indeed even the nature of any excessively-large-stack behavior) is unspecified. Some engines will throw an exception. More perniciously, others will arbitrarily limit the number of arguments actually passed to the applied function. (To illustrate this latter case: if such an engine had a limit of four arguments [actual limits are of course significantly higher], it would be as if the arguments <code>5, 6, 2, 3</code> had been passed to <code>apply</code> in the examples above, rather than the full array.) If your value array might grow into the tens of thousands, use a hybrid strategy: apply your function to chunks of the array at a time:</p> + +<pre class="brush: js">function minOfArray(arr) { + var min = Infinity; + var QUANTUM = 32768; + + for (var i = 0, len = arr.length; i < len; i += QUANTUM) { + var submin = Math.min.apply(null, + arr.slice(i, Math.min(i+QUANTUM, len))); + min = Math.min(submin, min); + } + + return min; +} + +var min = minOfArray([5, 6, 2, 3, 7]); +</pre> + +<h3 id="Using_apply_in_monkey-patching">Using apply in "monkey-patching"</h3> + +<p>Apply can be the best way to monkey-patch a built-in function of Firefox, or JS libraries. Given <code>someobject.foo</code> function, you can modify the function in a somewhat hacky way, like so:</p> + +<pre class="brush: js">var originalfoo = someobject.foo; +someobject.foo = function() { + // Do stuff before calling function + console.log(arguments); + // Call the function as it would have been called normally: + originalfoo.apply(this, arguments); + // Run stuff after, here. +} +</pre> + +<p>This method is especially handy where you want to debug events, or interface with something that has no API like the various <code>.on([event]...</code> events, such as those usable on the <a href="/en-US/docs/Tools/Page_Inspector#Developer_API">Devtools Inspector</a>).</p> + +<h2 id="規範">規範</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Initial definition. Implemented in JavaScript 1.3.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.3.4.3', 'Function.prototype.apply')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-function.prototype.apply', 'Function.prototype.apply')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-function.prototype.apply', 'Function.prototype.apply')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>ES 5.1 generic array-like object as {{jsxref("Functions/arguments", "arguments")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("2.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</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>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>ES 5.1 generic array-like object as {{jsxref("Functions/arguments", "arguments")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("2.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="參見">參見</h2> + +<ul> + <li>{{jsxref("Functions/arguments", "arguments")}} object</li> + <li>{{jsxref("Function.prototype.bind()")}}</li> + <li>{{jsxref("Function.prototype.call()")}}</li> + <li>{{jsxref("Functions", "Functions and function scope", "", 1)}}</li> + <li>{{jsxref("Reflect.apply()")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/function/bind/index.html b/files/zh-tw/web/javascript/reference/global_objects/function/bind/index.html new file mode 100644 index 0000000000..7092477133 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/function/bind/index.html @@ -0,0 +1,321 @@ +--- +title: Function.prototype.bind() +slug: Web/JavaScript/Reference/Global_Objects/Function/bind +translation_of: Web/JavaScript/Reference/Global_Objects/Function/bind +--- +<div>{{JSRef}}</div> + +<p><code><strong>bind()</strong></code> 方法,會建立一個新函式。該函式被呼叫時,會將 <code>this</code> 關鍵字設為給定的參數,並在呼叫時,帶有提供之前,給定順序的參數。</p> + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox"><var>fun</var>.bind(<var>thisArg</var>[, <var>arg1</var>[, <var>arg2</var>[, ...]]])</pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>thisArg</code></dt> + <dd>The value to be passed as the <code>this</code> parameter to the target function when the bound function is called. The value is ignored if the bound function is constructed using the {{jsxref("Operators/new", "new")}} operator.</dd> + <dt><code>arg1, arg2, ...</code></dt> + <dd>Arguments to prepend to arguments provided to the bound function when invoking the target function.</dd> +</dl> + +<h3 id="回傳值">回傳值</h3> + +<p>A copy of the given function with the specified <strong><code>this</code></strong> value and initial arguments.</p> + +<h2 id="敘述">敘述</h2> + +<p><strong>bind()</strong> 函式建立了一個新的<strong>綁定函式(BF)</strong>。<strong>BF</strong> 是個包裝了原有函式物件的 <strong>exotic function object</strong>(<strong>ECMAScript 2015</strong> 的術語)。通常,呼叫 <strong>BF</strong> 會執行該 <strong>wrapped function</strong>。<strong> BF</strong> 含有以下內部屬性:</p> + +<ul> + <li><strong>[[BoundTargetFunction]] </strong>- the wrapped function object;</li> + <li><strong>[[BoundThis]]</strong> - the value that is always passed as <strong>this</strong> value when calling the wrapped function.</li> + <li><strong>[[BoundArguments]]</strong> - a list of values whose elements are used as the first arguments to any call to the wrapped function.</li> + <li><strong>[[Call]]</strong> - executes code associated with this object. Invoked via a function call expression. The arguments to the internal method are a <strong>this</strong> value and a list containing the arguments passed to the function by a call expression.</li> +</ul> + +<p>When bound function is called, it calls internal method<strong> [[Call]]</strong> on <strong>[[BoundTargetFunction]], </strong>with following arguments <strong>Call(<em>boundThis</em>, <em>args</em>).</strong> Where, <strong><em>boundThis </em></strong>is <strong>[[BoundThis]]</strong>, <em><strong>args </strong></em>is <strong>[[BoundArguments]]</strong> followed by the arguments passed by the function call.</p> + +<p>A bound function may also be constructed using the <a href="/en-US/docs/Web/JavaScript/Reference/Operators/new" title="The new operator creates an instance of a user-defined object type or of one of the built-in object types that has a constructor function."><code>new</code></a> operator: doing so acts as though the target function had instead been constructed. The provided <strong><code>this</code></strong> value is ignored, while prepended arguments are provided to the emulated function.</p> + +<h2 id="範例">範例</h2> + +<h3 id="建立綁定函式">建立綁定函式</h3> + +<p>The simplest use of <code>bind()</code> is to make a function that, no matter how it is called, is called with a particular <strong><code>this</code></strong> value. A common mistake for new JavaScript programmers is to extract a method from an object, then to later call that function and expect it to use the original object as its <code>this</code> (e.g. by using that method in callback-based code). Without special care, however, the original object is usually lost. Creating a bound function from the function, using the original object, neatly solves this problem:</p> + +<pre class="brush: js">this.x = 9; // this refers to global "window" object here in the browser +var module = { + x: 81, + getX: function() { return this.x; } +}; + +module.getX(); // 81 + +var retrieveX = module.getX; +retrieveX(); +// returns 9 - The function gets invoked at the global scope + +// Create a new function with 'this' bound to module +// New programmers might confuse the +// global var x with module's property x +var boundGetX = retrieveX.bind(module); +boundGetX(); // 81 +</pre> + +<h3 id="Partially_applied_functions">Partially applied functions</h3> + +<p>The next simplest use of <code>bind()</code> is to make a function with pre-specified initial arguments. These arguments (if any) follow the provided <code>this</code> value and are then inserted at the start of the arguments passed to the target function, followed by the arguments passed to the bound function, whenever the bound function is called.</p> + +<pre class="brush: js">function list() { + return Array.prototype.slice.call(arguments); +} + +var list1 = list(1, 2, 3); // [1, 2, 3] + +// Create a function with a preset leading argument +var leadingThirtysevenList = list.bind(null, 37); + +var list2 = leadingThirtysevenList(); +// [37] + +var list3 = leadingThirtysevenList(1, 2, 3); +// [37, 1, 2, 3] +</pre> + +<h3 id="配合_setTimeout">配合 <code>setTimeout</code></h3> + +<p>By default within {{domxref("window.setTimeout()")}}, the <code>this</code> keyword will be set to the {{ domxref("window") }} (or <code>global</code>) object. When working with class methods that require <code>this</code> to refer to class instances, you may explicitly bind <code>this</code> to the callback function, in order to maintain the instance.</p> + +<pre class="brush: js">function LateBloomer() { + this.petalCount = Math.floor(Math.random() * 12) + 1; +} + +// Declare bloom after a delay of 1 second +LateBloomer.prototype.bloom = function() { + window.setTimeout(this.declare.bind(this), 1000); +}; + +LateBloomer.prototype.declare = function() { + console.log('I am a beautiful flower with ' + + this.petalCount + ' petals!'); +}; + +var flower = new LateBloomer(); +flower.bloom(); +// after 1 second, triggers the 'declare' method</pre> + +<h3 id="Bound_functions_used_as_constructors">Bound functions used as constructors</h3> + +<div class="warning"> +<p><strong>Warning:</strong> This section demonstrates JavaScript capabilities and documents some edge cases of the <code>bind()</code> method. The methods shown below are not the best way to do things and probably should not be used in any production environment.</p> +</div> + +<p>Bound functions are automatically suitable for use with the {{jsxref("Operators/new", "new")}} operator to construct new instances created by the target function. When a bound function is used to construct a value, the provided <code>this</code> is ignored. However, provided arguments are still prepended to the constructor call:</p> + +<pre class="brush: js">function Point(x, y) { + this.x = x; + this.y = y; +} + +Point.prototype.toString = function() { + return this.x + ',' + this.y; +}; + +var p = new Point(1, 2); +p.toString(); // '1,2' + +// not supported in the polyfill below, + +// works fine with native bind: + +var YAxisPoint = Point.bind(null, 0/*x*/); + + +var emptyObj = {}; +var YAxisPoint = Point.bind(emptyObj, 0/*x*/); + +var axisPoint = new YAxisPoint(5); +axisPoint.toString(); // '0,5' + +axisPoint instanceof Point; // true +axisPoint instanceof YAxisPoint; // true +new Point(17, 42) instanceof YAxisPoint; // true +</pre> + +<p>Note that you need do nothing special to create a bound function for use with {{jsxref("Operators/new", "new")}}. The corollary is that you need do nothing special to create a bound function to be called plainly, even if you would rather require the bound function to only be called using {{jsxref("Operators/new", "new")}}.</p> + +<pre class="brush: js">// Example can be run directly in your JavaScript console +// ...continuing from above + +// Can still be called as a normal function +// (although usually this is undesired) +YAxisPoint(13); + +emptyObj.x + ',' + emptyObj.y; +// > '0,13' +</pre> + +<p>If you wish to support the use of a bound function only using {{jsxref("Operators/new", "new")}}, or only by calling it, the target function must enforce that restriction.</p> + +<h3 id="Creating_shortcuts">Creating shortcuts</h3> + +<p><code>bind()</code> is also helpful in cases where you want to create a shortcut to a function which requires a specific <strong><code>this</code></strong> value.</p> + +<p>Take {{jsxref("Array.prototype.slice")}}, for example, which you want to use for converting an array-like object to a real array. You could create a shortcut like this:</p> + +<pre class="brush: js">var slice = Array.prototype.slice; + +// ... + +slice.apply(arguments); +</pre> + +<p>With <code>bind()</code>, this can be simplified. In the following piece of code, <code>slice</code> is a bound function to the {{jsxref("Function.prototype.apply()", "apply()")}} function of {{jsxref("Function.prototype")}}, with the <strong><code>this</code></strong> value set to the {{jsxref("Array.prototype.slice()", "slice()")}} function of {{jsxref("Array.prototype")}}. This means that additional <code>apply()</code> calls can be eliminated:</p> + +<pre class="brush: js">// same as "slice" in the previous example +var unboundSlice = Array.prototype.slice; +var slice = Function.prototype.apply.bind(unboundSlice); + +// ... + +slice(arguments); +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p>You can partially work around this by inserting the following code at the beginning of your scripts, allowing use of much of the functionality of <code>bind()</code> in implementations that do not natively support it.</p> + +<pre class="brush: js">if (!Function.prototype.bind) { + Function.prototype.bind = function(oThis) { + if (typeof this !== 'function') { + // closest thing possible to the ECMAScript 5 + // internal IsCallable function + throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable'); + } + + var aArgs = Array.prototype.slice.call(arguments, 1), + fToBind = this, + fNOP = function() {}, + fBound = function() { + return fToBind.apply(this instanceof fNOP + ? this + : oThis, + aArgs.concat(Array.prototype.slice.call(arguments))); + }; + + if (this.prototype) { + // Function.prototype doesn't have a prototype property + fNOP.prototype = this.prototype; + } + fBound.prototype = new fNOP(); + + return fBound; + }; +} +</pre> + +<p>Some of the many differences (there may well be others, as this list does not seriously attempt to be exhaustive) between this algorithm and the specified algorithm are:</p> + +<ul> + <li>The partial implementation relies on {{jsxref("Array.prototype.slice()")}}, {{jsxref("Array.prototype.concat()")}}, {{jsxref("Function.prototype.call()")}} and {{jsxref("Function.prototype.apply()")}}, built-in methods to have their original values.</li> + <li>The partial implementation creates functions that do not have immutable "poison pill" {{jsxref("Function.caller", "caller")}} and <code>arguments</code> properties that throw a {{jsxref("Global_Objects/TypeError", "TypeError")}} upon get, set, or deletion. (This could be added if the implementation supports {{jsxref("Object.defineProperty")}}, or partially implemented [without throw-on-delete behavior] if the implementation supports the {{jsxref("Object.defineGetter", "__defineGetter__")}} and {{jsxref("Object.defineSetter", "__defineSetter__")}} extensions.)</li> + <li>The partial implementation creates functions that have a <code>prototype</code> property. (Proper bound functions have none.)</li> + <li>The partial implementation creates bound functions whose {{jsxref("Function.length", "length")}} property does not agree with that mandated by ECMA-262: it creates functions with length 0, while a full implementation, depending on the length of the target function and the number of pre-specified arguments, may return a non-zero length.</li> +</ul> + +<p>If you choose to use this partial implementation, <strong>you must not rely on those cases where behavior deviates from ECMA-262, 5th edition!</strong> With some care, however (and perhaps with additional modification to suit specific needs), this partial implementation may be a reasonable bridge to the time when <code>bind()</code> is widely implemented according to the specification.</p> + +<p>Please check <a href="https://github.com/Raynos/function-bind">https://github.com/Raynos/function-bind</a> for a more thorough solution!</p> + +<h2 id="規範">規範</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.3.4.5', 'Function.prototype.bind')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.8.5.</td> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-function.prototype.bind', 'Function.prototype.bind')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-function.prototype.bind', 'Function.prototype.bind')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome("7")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("2")}}</td> + <td>{{CompatIE("9")}}</td> + <td>{{CompatOpera("11.60")}}</td> + <td>{{CompatSafari("5.1")}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatAndroid("4.0")}}</td> + <td>{{CompatChrome("1")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("2")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatOperaMobile("11.5")}}</td> + <td>{{CompatSafari("6.0")}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="相關連結">相關連結</h2> + +<ul> + <li>{{jsxref("Function.prototype.apply()")}}</li> + <li>{{jsxref("Function.prototype.call()")}}</li> + <li>{{jsxref("Functions", "Functions", "", 1)}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/function/call/index.html b/files/zh-tw/web/javascript/reference/global_objects/function/call/index.html new file mode 100644 index 0000000000..1d1d2017ee --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/function/call/index.html @@ -0,0 +1,105 @@ +--- +title: Function.prototype.call +slug: Web/JavaScript/Reference/Global_Objects/Function/call +translation_of: Web/JavaScript/Reference/Global_Objects/Function/call +--- +<p>{{JSRef}}</p> + +<h2 id="概述">概述</h2> + +<p>使用給定的<code>this</code>參數以及分別給定的參數來呼叫某個函數</p> + +<div class="note"><strong>附註:</strong> 此函數的所有語法大致上與<code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Function/apply" title="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/apply">apply()</a></code>相同,他們基本上不同處只有 <code>call()</code> 接受一連串的參數,而 <code>apply()</code> 單一的array作為參數</div> + +<table class="standard-table"> + <thead> + <tr> + <th class="header" colspan="2"><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Function" title="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function </a>物件的方法</th> + </tr> + </thead> + <tbody> + <tr> + <td>被實作於</td> + <td>JavaScript 1.3</td> + </tr> + <tr> + <td>ECMAScript 版本</td> + <td>ECMAScript 第三版</td> + </tr> + </tbody> +</table> + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox"><code><em>fun</em>.call(<em>thisArg</em>[, <em>arg1</em>[, <em>arg2</em>[, ...]]])</code></pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>thisArg</code></dt> + <dd>呼叫<em><code>fun</code></em>時提供的<code>this</code>值。 注意,它可能是一個無法在函數內看到的值:若這個函數是在非嚴苛模式( <a href="/en-US/docs/JavaScript/Reference/Functions_and_function_scope/Strict_mode" title="JavaScript/Strict mode">non-strict mode</a> ), <code>null</code> <code>、undefined</code> 將會被置換成全域變數,而原生型態的值將會被封裝</dd> + <dt><code>arg1, arg2, ...</code></dt> + <dd>其他參數</dd> +</dl> + +<h2 id="描述">描述</h2> + +<p>你可以在呼叫一個現存的函數時,使用不一樣的 <code>this</code> 物件。 <code>this</code> 會參照到目前的物件,呼叫的物件上</p> + +<p>使用 <code>call,</code> 你可以實作函數一次,然後在其他的物件上直接繼承它,而不用在新的物件上重寫該函數</p> + +<h2 id="範例">範例</h2> + +<h3 id="使用_call_來串接物件上的建構子">使用 <code>call</code> 來串接物件上的建構子</h3> + +<p>你可以使用 <code>call</code> 來串接其他物件的建構子,就像 Java. 下面的例子中,<code>Product</code> 物件的建構子定義了兩個參數 <code>name</code> 以及 <code>price</code>. 其他函數<code>Food</code> 及 <code>Toy</code> 引用了 <code>Product</code> 並傳入 <code>this</code> 、 <code>name</code> 和 <code>price</code>。 Product 初始化它的屬性 <code>name</code> 和 <code>price</code>, 而兩個子函數則定義了<code>category。</code></p> + +<pre class="brush: js">function Product(name, price) { + this.name = name; + this.price = price; + + if (price < 0) + throw RangeError('Cannot create product "' + name + '" with a negative price'); + return this; +} + +function Food(name, price) { + Product.call(this, name, price); + this.category = 'food'; +} +Food.prototype = new Product(); + +function Toy(name, price) { + Product.call(this, name, price); + this.category = 'toy'; +} +Toy.prototype = new Product(); + +var cheese = new Food('feta', 5); +var fun = new Toy('robot', 40); +</pre> + +<h3 id="使用_call_來呼叫匿名的函數">使用 <code>call</code> 來呼叫匿名的函數</h3> + +<p>下面這個簡易的例子中,我們做了一個匿名的函數,並用 <code>call</code> 來讓它應用在每個在串列中的物件中. 這個匿名函數的主要用途是加入一個print函數到每個物件上,這個函數可以印出每個物件的index指標。 傳入物件作為 <code>this</code> 的值並不是必要的,但他有解釋的用途。</p> + +<pre class="brush: js">var animals = [ + {species: 'Lion', name: 'King'}, + {species: 'Whale', name: 'Fail'} +]; + +for (var i = 0; i < animals.length; i++) { + (function (i) { + this.print = function () { + console.log('#' + i + ' ' + this.species + ': ' + this.name); + } + this.print(); + }).call(animals[i], i); +} +</pre> + +<h2 id="參見">參見</h2> + +<ul> + <li><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Function/apply" title="JavaScript/Reference/Global_Objects/Function/apply">apply</a></li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/function/index.html b/files/zh-tw/web/javascript/reference/global_objects/function/index.html new file mode 100644 index 0000000000..b88c087b24 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/function/index.html @@ -0,0 +1,191 @@ +--- +title: Function +slug: Web/JavaScript/Reference/Global_Objects/Function +tags: + - JavaScript + - JavaScript Reference + - NeedsTranslation + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/Function +--- +<div>{{JSRef}}</div> + +<p><strong><code>Function</code> 建構函式</strong>可建立一個新的 <code>Function</code> 物件。在 JavaScript 中,所有的函式實際上都是 <code>Function</code> 物件。</p> + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox"><code>new Function ([<var>arg1</var>[, <var>arg2</var>[, ...<var>argN</var>]],] <var>functionBody</var>)</code></pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>arg1, arg2, ... arg<em>N</em></code></dt> + <dd>function 的引數名稱必須要符合正規的命名。每個名稱都必須要是有效的 JavaScript 識別符號規則的字串,或是使用英文逗號「, 」分隔開的字串清單; 像是 "x", "theValue", 或是 "a, b'。</dd> + <dt><code>functionBody</code></dt> + <dd><span class="_3oh- _58nk">包含 JavaScript 狀態以及 function 定義的字串。</span></dd> +</dl> + +<h2 id="描述">描述</h2> + +<p><code>Function</code> objects created with the <code>Function</code> constructor are parsed when the function is created. This is less efficient than declaring a function with a <a href="/zh-TW/docs/Web/JavaScript/Reference/Operators/function">function expression</a> or <a href="/zh-TW/docs/Web/JavaScript/Reference/Statements/function">function statement</a> and calling it within your code, because such functions are parsed with the rest of the code.</p> + +<p>All arguments passed to the function are treated as the names of the identifiers of the parameters in the function to be created, in the order in which they are passed.</p> + +<p>Invoking the <code>Function</code> constructor as a function (without using the <code>new</code> operator) has the same effect as invoking it as a constructor.</p> + +<h2 id="Function_的屬性與方法"><code>Function</code> <code>的屬性與方法</code></h2> + +<p>The global <code>Function</code> object has no methods or properties of its own, however, since it is a function itself it does inherit some methods and properties through the prototype chain from {{jsxref("Function.prototype")}}.</p> + +<h2 id="Function_原型物件"><code>Function</code> 原型物件</h2> + +<h3 id="屬性_Properties">屬性 Properties</h3> + +<div>{{page('/zh-TW/docs/JavaScript/Reference/Global_Objects/Function/prototype', 'Properties')}}</div> + +<h3 id="方法_Methods">方法 Methods</h3> + +<div>{{page('/zh-TW/docs/JavaScript/Reference/Global_Objects/Function/prototype', 'Methods')}}</div> + +<h2 id="Function_實例"><code>Function</code> 實例</h2> + +<p><code>Function</code> instances inherit methods and properties from {{jsxref("Function.prototype")}}. As with all constructors, you can change the constructor's prototype object to make changes to all <code>Function</code> instances.</p> + +<h2 id="範例">範例</h2> + +<h3 id="Specifying_arguments_with_the_Function_constructor">Specifying arguments with the <code>Function</code> constructor</h3> + +<p>The following code creates a <code>Function</code> object that takes two arguments.</p> + +<pre class="brush: js">// Example can be run directly in your JavaScript console + +// Create a function that takes two arguments and returns the sum of those arguments +var adder = new Function('a', 'b', 'return a + b'); + +// Call the function +adder(2, 6); +// > 8 +</pre> + +<p>The arguments "<code>a</code>" and "<code>b</code>" are formal argument names that are used in the function body, "<code>return a + b</code>".</p> + +<h3 id="Difference_between_Function_constructor_and_function_declaration">Difference between Function constructor and function declaration</h3> + +<p>Functions created with the <code>Function</code> constructor do not create closures to their creation contexts; they always are created in the global scope. When running them, they will only be able to access their own local variables and global ones, not the ones from the scope in which the <code>Function</code> constructor was called. This is different from using {{jsxref("eval")}} with code for a function expression.</p> + +<pre class="brush: js">var x = 10; + +function createFunction1() { + var x = 20; + return new Function('return x;'); // this |x| refers global |x| +} + +function createFunction2() { + var x = 20; + function f() { + return x; // this |x| refers local |x| above + } + return f; +} + +var f1 = createFunction1(); +console.log(f1()); // 10 +var f2 = createFunction2(); +console.log(f2()); // 20 +</pre> + +<h2 id="規範">規範</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.3', 'Function')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-function-objects', 'Function')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-function-objects', 'Function')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</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>Feature</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>Basic support</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>{{jsxref("Functions", "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/zh-tw/web/javascript/reference/global_objects/function/length/index.html b/files/zh-tw/web/javascript/reference/global_objects/function/length/index.html new file mode 100644 index 0000000000..699e1ff178 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/function/length/index.html @@ -0,0 +1,144 @@ +--- +title: Function.length +slug: Web/JavaScript/Reference/Global_Objects/Function/length +translation_of: Web/JavaScript/Reference/Global_Objects/Function/length +--- +<div>{{JSRef}}</div> + +<p><code><strong>length</strong></code> property表示該 function 預期被傳入的參數數量</p> + +<div>{{js_property_attributes(0,0,1)}}</div> + +<h2 id="描述">描述</h2> + +<p><code>length</code> 是 function 物件的一個 property,表示該 function 預期被傳入的參數數量,這個數量並不包含 {{jsxref("rest_parameters", "rest parameter", "", 1)}} 且只包涵第一個預設參數(Default Parameters)前的參數。相較之下 {{jsxref("Functions_and_function_scope/arguments/length", "arguments.length")}} 是 function 內部的物件,會提供真正傳進 function 中的參數數量。</p> + +<h3 id="Function_建構子的_data_property"><code>Function</code> 建構子的 data property</h3> + +<p>{{jsxref("Function")}} 建構子本身就是一個 {{jsxref("Function")}} 物件。其 <code>length</code> data property 的值為 1。此 property 的 attributes 包含: Writable: <code>false</code>, Enumerable: <code>false</code>, Configurable: <code>true</code>.</p> + +<h3 id="Function_prototype_物件的_property"><code>Function</code> prototype 物件的 property</h3> + +<p>{{jsxref("Function")}} prototype 物件的 length property 其值為 0。</p> + +<h2 id="範例">範例</h2> + +<pre class="brush: js">console.log(Function.length); /* 1 */ + +console.log((function() {}).length); /* 0 */ +console.log((function(a) {}).length); /* 1 */ +console.log((function(a, b) {}).length); /* 2 以此類推. */ + +console.log((function(...args) {}).length); /* 0, rest parameter 不包含在內 */ + +console.log((function(a, b = 1, c) {}).length); /* 1 */ +// 只有在預設參數前的參數會被算到,也就是只有 a 會被視為必須傳入的參數 +// 而 c 將被預設為 undefined +</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('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>最初的定義,在 JavaScript 1.1 中實作。</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.3.5.1', 'Function.length')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-function-instances-length', 'Function.length')}}</td> + <td>{{Spec2('ES6')}}</td> + <td><code>此 </code>property 的 <code>configurable</code> attribute 現在為 <code>true</code>.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-function-instances-length', 'Function.length')}}</td> + <td>{{Spec2('ESDraft')}}</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>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>Configurable: true</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop(37)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</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>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>Configurable: true</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile(37)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="可參閱">可參閱</h2> + +<ul> + <li>{{jsxref("Function")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/function/prototype/index.html b/files/zh-tw/web/javascript/reference/global_objects/function/prototype/index.html new file mode 100644 index 0000000000..1db46bc59a --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/function/prototype/index.html @@ -0,0 +1,138 @@ +--- +title: Function.prototype +slug: Web/JavaScript/Reference/Global_Objects/Function/prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Function +--- +<div>{{JSRef}}</div> + +<p><code><strong>Function.prototype</strong></code> 屬性表示 {{jsxref("Function")}} 的原型物件。</p> + +<h2 id="描述">描述</h2> + +<p>{{jsxref("Function")}} objects inherit from <code>Function.prototype</code>. <code>Function.prototype</code> cannot be modified.</p> + +<h2 id="屬性">屬性</h2> + +<dl> + <dt>{{jsxref("Function.arguments")}} {{deprecated_inline}}</dt> + <dd>An array corresponding to the arguments passed to a function. This is deprecated as property of {{jsxref("Function")}}, use the {{jsxref("Functions/arguments", "arguments")}} object available within the function instead.</dd> + <dt><s class="obsoleteElement">{{jsxref("Function.arity")}} {{obsolete_inline}}</s></dt> + <dd><s class="obsoleteElement">Used to specifiy the number of arguments expected by the function, but has been removed. Use the {{jsxref("Function.length", "length")}} property instead.</s></dd> + <dt>{{jsxref("Function.caller")}} {{non-standard_inline}}</dt> + <dd>Specifies the function that invoked the currently executing function.</dd> + <dt>{{jsxref("Function.length")}}</dt> + <dd>Specifies the number of arguments expected by the function.</dd> + <dt>{{jsxref("Function.name")}}</dt> + <dd>The name of the function.</dd> + <dt>{{jsxref("Function.displayName")}} {{non-standard_inline}}</dt> + <dd>The display name of the function.</dd> + <dt><code>Function.prototype.constructor</code></dt> + <dd>Specifies the function that creates an object's prototype. See {{jsxref("Object.prototype.constructor")}} for more details.</dd> +</dl> + +<h2 id="方法">方法</h2> + +<dl> + <dt>{{jsxref("Function.prototype.apply()")}}</dt> + <dd>Calls a function and sets its <em>this</em> to the provided value, arguments can be passed as an {{jsxref("Array")}} object.</dd> + <dt>{{jsxref("Function.prototype.bind()")}}</dt> + <dd>Creates a new function which, when called, has its <em>this</em> set to the provided value, with a given sequence of arguments preceding any provided when the new function was called.</dd> + <dt>{{jsxref("Function.prototype.call()")}}</dt> + <dd>Calls (executes) a function and sets its <em>this</em> to the provided value, arguments can be passed as they are.</dd> + <dt>{{jsxref("Function.prototype.isGenerator()")}} {{non-standard_inline}}</dt> + <dd>Returns <code>true</code> if the function is a <a href="/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators">generator</a>; otherwise returns <code>false</code>.</dd> + <dt>{{jsxref("Function.prototype.toSource()")}} {{non-standard_inline}}</dt> + <dd>Returns a string representing the source code of the function. Overrides the {{jsxref("Object.prototype.toSource")}} method.</dd> + <dt>{{jsxref("Function.prototype.toString()")}}</dt> + <dd>Returns a string representing the source code of the function. Overrides the {{jsxref("Object.prototype.toString")}} method.</dd> +</dl> + +<h2 id="規範">規範</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.1</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.3.5.2', 'Function.prototype')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-function-instances-prototype', 'Function.prototype')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-function-instances-prototype', 'Function.prototype')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</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>Feature</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>Basic support</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>{{jsxref("Function")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/index.html b/files/zh-tw/web/javascript/reference/global_objects/index.html new file mode 100644 index 0000000000..c9e81579fb --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/index.html @@ -0,0 +1,201 @@ +--- +title: 標準內建物件 +slug: Web/JavaScript/Reference/Global_Objects +tags: + - JavaScript + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects +--- +<div>{{jsSidebar("Objects")}}</div> + +<p>本章節記錄了 JavaScript 所有標準、內建的物件,以及這些物件的方法與屬性。</p> + +<p>「全域物件」(或稱作標準內建物件)這個專有名字並非是要和<strong>全域物件</strong>混著說。在這裡,全域物件是那些在全域範圍裡的物件。而<strong>全域物件</strong>自身則是關聯到全域範圍裡的 {{jsxref("Operators/this", "this")}} 運算子(但若是在 ECMAScript 5 的嚴格模式(strict mode)則是不被採用的,即會回傳 {{jsxref("undefined")}})。 事實上,全域範圍包含了全域物件的屬性,也包含了繼承而來的屬性(如果有的話)。</p> + +<p>其他在全域範疇的物件,不是<a href="/zh-TW/docs/Web/JavaScript/Guide/Working_with_Objects#Creating_new_objects">被使用者的腳本建立</a>,就是由主體的應用程式所提供。 主體物件是由 <a href="/zh-TW/docs/Web/API/Reference">API 參考資料</a>定義的文件決定瀏覽器環境中是否可用。 更多關於 <a href="/zh-TW/docs/DOM/DOM_Reference">DOM</a> 和 <a href="/zh-TW/docs/Web/JavaScript">JavaScript</a> 核心的差異,請參考 <a href="/zh-TW/docs/Web/JavaScript/JavaScript_technologies_overview">JavaScript 技術概要</a>。</p> + +<h2 id="標準物件分類">標準物件分類</h2> + +<h3 id="數值屬性">數值屬性</h3> + +<p>這些全域屬性會返回一個值;全域屬性本身不擁有任何屬性和函式。</p> + +<ul> + <li>{{jsxref("Infinity")}}</li> + <li>{{jsxref("NaN")}}</li> + <li>{{jsxref("undefined")}}</li> + <li>{{jsxref("null")}} literal</li> +</ul> + +<h3 id="函數屬性">函數屬性</h3> + +<p>這些全域函式會直接在全域範圍中被呼叫,不用從某個物件取得後呼叫;呼叫後直接回傳結果給執行的人。</p> + +<ul> + <li>{{jsxref("Global_Objects/eval", "eval()")}}</li> + <li>{{jsxref("Global_Objects/uneval", "uneval()")}} {{non-standard_inline}}</li> + <li>{{jsxref("Global_Objects/isFinite", "isFinite()")}}</li> + <li>{{jsxref("Global_Objects/isNaN", "isNaN()")}}</li> + <li>{{jsxref("Global_Objects/parseFloat", "parseFloat()")}}</li> + <li>{{jsxref("Global_Objects/parseInt", "parseInt()")}}</li> + <li>{{jsxref("Global_Objects/decodeURI", "decodeURI()")}}</li> + <li>{{jsxref("Global_Objects/decodeURIComponent", "decodeURIComponent()")}}</li> + <li>{{jsxref("Global_Objects/encodeURI", "encodeURI()")}}</li> + <li>{{jsxref("Global_Objects/encodeURIComponent", "encodeURIComponent()")}}</li> + <li>{{jsxref("Global_Objects/escape", "escape()")}} {{deprecated_inline}}</li> + <li>{{jsxref("Global_Objects/unescape", "unescape()")}} {{deprecated_inline}}</li> +</ul> + +<h3 id="基礎物件">基礎物件</h3> + +<p>這裡所陳列稱為基礎物件,將作為其他所有物件的母物件。包含了一般物件、函式以及錯誤。</p> + +<ul> + <li>{{jsxref("Object")}}</li> + <li>{{jsxref("Function")}}</li> + <li>{{jsxref("Boolean")}}</li> + <li>{{jsxref("Symbol")}}</li> + <li>{{jsxref("Error")}}</li> + <li>{{jsxref("EvalError")}}</li> + <li>{{jsxref("InternalError")}}</li> + <li>{{jsxref("RangeError")}}</li> + <li>{{jsxref("ReferenceError")}}</li> + <li>{{jsxref("SyntaxError")}}</li> + <li>{{jsxref("TypeError")}}</li> + <li>{{jsxref("URIError")}}</li> +</ul> + +<h3 id="數字與日期">數字與日期</h3> + +<p>這裡陳列了數字、日期及數學運算。</p> + +<ul> + <li>{{jsxref("Number")}}</li> + <li>{{jsxref("Math")}}</li> + <li>{{jsxref("Date")}}</li> +</ul> + +<h3 id="文字處理">文字處理</h3> + +<p>These objects represent strings and support manipulating them.</p> + +<ul> + <li>{{jsxref("String")}}</li> + <li>{{jsxref("RegExp")}}</li> +</ul> + +<h3 id="具索引的集合">具索引的集合</h3> + +<p>These objects represent collections of data which are ordered by an index value. This includes (typed) arrays and array-like constructs.</p> + +<ul> + <li>{{jsxref("Array")}}</li> + <li>{{jsxref("Int8Array")}}</li> + <li>{{jsxref("Uint8Array")}}</li> + <li>{{jsxref("Uint8ClampedArray")}}</li> + <li>{{jsxref("Int16Array")}}</li> + <li>{{jsxref("Uint16Array")}}</li> + <li>{{jsxref("Int32Array")}}</li> + <li>{{jsxref("Uint32Array")}}</li> + <li>{{jsxref("Float32Array")}}</li> + <li>{{jsxref("Float64Array")}}</li> +</ul> + +<h3 id="具鍵值的集合">具鍵值的集合</h3> + +<p>These objects represent collections which use keys; these contain elements which are iterable in the order of insertion.</p> + +<ul> + <li>{{jsxref("Map")}}</li> + <li>{{jsxref("Set")}}</li> + <li>{{jsxref("WeakMap")}}</li> + <li>{{jsxref("WeakSet")}}</li> +</ul> + +<h3 id="向量集合">向量集合</h3> + +<p>{{Glossary("SIMD")}} vector data types are objects where data is arranged into lanes.</p> + +<ul> + <li>{{jsxref("SIMD")}} {{experimental_inline}}</li> + <li>{{jsxref("Float32x4", "SIMD.Float32x4")}} {{experimental_inline}}</li> + <li>{{jsxref("Float64x2", "SIMD.Float64x2")}} {{experimental_inline}}</li> + <li>{{jsxref("Int8x16", "SIMD.Int8x16")}} {{experimental_inline}}</li> + <li>{{jsxref("Int16x8", "SIMD.Int16x8")}} {{experimental_inline}}</li> + <li>{{jsxref("Int32x4", "SIMD.Int32x4")}} {{experimental_inline}}</li> + <li>{{jsxref("Uint8x16", "SIMD.Uint8x16")}} {{experimental_inline}}</li> + <li>{{jsxref("Uint16x8", "SIMD.Uint16x8")}} {{experimental_inline}}</li> + <li>{{jsxref("Uint32x4", "SIMD.Uint32x4")}} {{experimental_inline}}</li> + <li>{{jsxref("Bool8x16", "SIMD.Bool8x16")}} {{experimental_inline}}</li> + <li>{{jsxref("Bool16x8", "SIMD.Bool16x8")}} {{experimental_inline}}</li> + <li>{{jsxref("Bool32x4", "SIMD.Bool32x4")}} {{experimental_inline}}</li> + <li>{{jsxref("Bool64x2", "SIMD.Bool64x2")}} {{experimental_inline}}</li> +</ul> + +<h3 id="結構化資料">結構化資料</h3> + +<p>These objects represent and interact with structured data buffers and data coded using JavaScript Object Notation (JSON).</p> + +<ul> + <li>{{jsxref("ArrayBuffer")}}</li> + <li>{{jsxref("SharedArrayBuffer")}} {{experimental_inline}}</li> + <li>{{jsxref("Atomics")}} {{experimental_inline}}</li> + <li>{{jsxref("DataView")}}</li> + <li>{{jsxref("JSON")}}</li> +</ul> + +<h3 id="控制抽象化物件">控制抽象化物件</h3> + +<ul> + <li>{{jsxref("Promise")}}</li> + <li>{{jsxref("Generator")}}</li> + <li>{{jsxref("GeneratorFunction")}}</li> + <li>{{experimental_inline}} {{jsxref("AsyncFunction")}}</li> +</ul> + +<h3 id="Reflection">Reflection</h3> + +<ul> + <li>{{jsxref("Reflect")}}</li> + <li>{{jsxref("Proxy")}}</li> +</ul> + +<h3 id="國際化">國際化</h3> + +<p>Additions to the ECMAScript core for language-sensitive functionalities.</p> + +<ul> + <li>{{jsxref("Intl")}}</li> + <li>{{jsxref("Global_Objects/Collator", "Intl.Collator")}}</li> + <li>{{jsxref("Global_Objects/DateTimeFormat", "Intl.DateTimeFormat")}}</li> + <li>{{jsxref("Global_Objects/NumberFormat", "Intl.NumberFormat")}}</li> +</ul> + +<h3 id="WebAssembly">WebAssembly</h3> + +<ul> + <li>{{jsxref("WebAssembly")}}</li> + <li>{{jsxref("WebAssembly.Module")}}</li> + <li>{{jsxref("WebAssembly.Instance")}}</li> + <li>{{jsxref("WebAssembly.Memory")}}</li> + <li>{{jsxref("WebAssembly.Table")}}</li> + <li>{{jsxref("WebAssembly.CompileError")}}</li> + <li>{{jsxref("WebAssembly.LinkError")}}</li> + <li>{{jsxref("WebAssembly.RuntimeError")}}</li> +</ul> + +<h3 id="非標準物件">非標準物件</h3> + +<ul> + <li>{{jsxref("Iterator")}} {{non-standard_inline}}</li> + <li>{{jsxref("ParallelArray")}} {{non-standard_inline}}</li> + <li>{{jsxref("StopIteration")}} {{non-standard_inline}}</li> +</ul> + +<h3 id="其他">其他</h3> + +<ul> + <li><code><a href="/docs/Web/JavaScript/Reference/Functions/arguments">arguments</a></code></li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/infinity/index.html b/files/zh-tw/web/javascript/reference/global_objects/infinity/index.html new file mode 100644 index 0000000000..147914eea7 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/infinity/index.html @@ -0,0 +1,76 @@ +--- +title: Infinity +slug: Web/JavaScript/Reference/Global_Objects/Infinity +translation_of: Web/JavaScript/Reference/Global_Objects/Infinity +--- +<div>{{jsSidebar("Objects")}}</div> + +<p>全域 <code><strong>Infinity</strong></code> 屬性是一個表示無窮大的數值。</p> + +<p>{{js_property_attributes(0,0,0)}}</p> + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox"><code>Infinity </code></pre> + +<h2 id="描述">描述</h2> + +<p><code>Infinity</code> 是全域物件屬性,即它是全域範圍內的變數。</p> + +<p><code>Infinity</code> 的初始值是 {{jsxref("Number.POSITIVE_INFINITY")}} <code>Infinity</code> 值(正無窮大)值大於其他任何數值。該值在數學上表現為無窮大。例如,任何乘以 <code>Infinity</code> 的正整數都是 <code>Infinity</code>,除以 <code>Infinity</code> 的任何數都是 0。</p> + +<p>按照 ECMAScript 5 規範,在 JavaScript 1.8.5 / Firefox 4 實作的 <code>Infinity</code> 乃唯讀屬性。</p> + +<h2 id="範例">範例</h2> + +<pre class="brush: js">console.log(Infinity ); /* Infinity */ +console.log(Infinity + 1 ); /* Infinity */ +console.log(Math.pow(10,1000)); /* Infinity */ +console.log(Math.log(0) ); /* -Infinity */ +console.log(1 / Infinity ); /* 0 */ +</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('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>初始定義。在 JavaScript 1.3 實作。</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.1.1.2', 'Infinity')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-value-properties-of-the-global-object-infinity', 'Infinity')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-value-properties-of-the-global-object-infinity', 'Infinity')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<p>{{Compat("javascript.builtins.Infinity")}}</p> + + +<h2 id="參見">參見</h2> + +<ul> + <li>{{jsxref("Number.NEGATIVE_INFINITY")}}</li> + <li>{{jsxref("Number.POSITIVE_INFINITY")}}</li> + <li>{{jsxref("Number.isFinite")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/isnan/index.html b/files/zh-tw/web/javascript/reference/global_objects/isnan/index.html new file mode 100644 index 0000000000..6f055cb8fa --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/isnan/index.html @@ -0,0 +1,183 @@ +--- +title: isNaN() +slug: Web/JavaScript/Reference/Global_Objects/isNaN +translation_of: Web/JavaScript/Reference/Global_Objects/isNaN +--- +<div>{{jsSidebar("Objects")}}</div> + +<p><code><strong>isNaN()</strong></code> 函式會判斷某個數值是不是 {{jsxref("NaN")}}。注意:在 <code>isNaN</code> 函式裡面,有個<a href="#描述">有趣的</a>強制性規則。你可能會想改用在 ECMAScript 2015 導入的 {{jsxref("Number.isNaN()")}}。</p> + +<div>{{EmbedInteractiveExample("pages/js/globalprops-isnan.html")}}</div> + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox"><code>isNaN(<em>value</em>)</code></pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>value</code></dt> + <dd>要測試的數值。</dd> +</dl> + +<h3 id="回傳值">回傳值</h3> + +<p>如果給定值是 {{jsxref("NaN")}} 就回傳 <strong><code>true</code></strong>、否則就回傳 <strong><code>false</code></strong>。</p> + +<h2 id="描述">描述</h2> + +<h3 id="為什麼要用_isNaN_函式">為什麼要用 <code>isNaN</code> 函式</h3> + +<p>與其他 JavaScript 的值不同,你不可能靠等號運算符(== 與 ===)來判斷某個值是不是 {{jsxref("NaN")}},因為連 <code>NaN == NaN</code> 與 <code>NaN === NaN</code> 的結果都是 <code>false</code>。因此,<code>isNaN</code> 函式是必要的。</p> + +<h3 id="NaN_值的來源"><code>NaN</code> 值的來源</h3> + +<p><code>NaN</code> 會在算術運算(arithmetic operations)出現 <em>undefined</em> 或是 <em>unrepresentable</em> 值的結果時產生。這些值不一定是溢出條件。<code>NaN</code> 亦為試圖給毫無可用數字的原始值、予以強制運算之結果。</p> + +<p>例如,零除以零的結果會是 <code>NaN</code>——不過把其他數字除以零則不是 <code>NaN</code>。</p> + +<h3 id="令人困惑的特殊狀況行為">令人困惑的特殊狀況行為</h3> + +<p>從最早的 <code>isNaN</code> 函式版本規範始,其針對非數值之行為,不斷教人困惑至極。當 <code>isNaN</code> 函式的參數並非<a href="http://es5.github.com/#x8.5" title="http://es5.github.com/#x8.5">數字</a>型別時,此值會先強制轉換到數字。該值接著會測定此值是否為 {{jsxref("NaN")}}。因此,當被強制轉換的非數字,給出了有效的非 NaN 值(經典案例為空的字串與布林原始值:它們在強制轉換時,會給予數字結果 0 或 1)時,會回傳不如預期的「false」值:以空的字串為例,它很明顯地「非數字」。這段教人糾結的點,乃出於「非數字」術語的「數字」一詞、由 IEEE-754 浮點值定義之事實而來。這個函式要解釋為「當這個值,被強制轉換為數值時,它還是 IEEE-754 的『非數字』值嗎?」的答案。</p> + +<p>最新的 ECMAScript(ES2015)版本導入了 {{jsxref("Number.isNaN()")}} 函式。儘管 <code>Number.isNaN</code> 的 <code>NaN</code> 依舊維持了數字上的意義、而不是簡單的「非數字」,<code>Number.isNaN(x)</code> 在偵測 <code>x</code> 為 <code>NaN</code> 與否時比較可靠。另外,如果在缺少 <code>Number.isNaN</code> 的情況下,通過表達式<code>(x != x)</code> 來檢測變量<code>x</code>是否是NaN會更加的可靠。</p> + +<p>一個 <code>isNaN</code> 的 polyfill 可以理解為(這個 polyfill 利用了 <code>NaN</code> 自身永不等於自身這一特性):</p> + +<pre class="brush: js">var isNaN = function(value) { + var n = Number(value); + return n !== n; +};</pre> + +<h2 id="範例">範例</h2> + +<pre class="brush: js">isNaN(NaN); // true +isNaN(undefined); // true +isNaN({}); // true + +isNaN(true); // false +isNaN(null); // false +isNaN(37); // false + +// 字串 +isNaN("37"); // false: "37" 轉換成數字的 37 後就不是 NaN 了 +isNaN("37.37"); // false: "37.37" 轉換成數字的 37.37 後就不是 NaN 了 +isNaN("123ABC"); // true: parseInt("123ABC") 是 123 但 Number("123ABC") 是 NaN +isNaN(""); // false: 空字串轉換成數字的 0 後就不是 NaN 了 +isNaN(" "); // false: 有空白的字串轉換成數字的 0 後就不是 NaN 了 + +// 日期 +isNaN(new Date()); // false +isNaN(new Date().toString()); // true + +// 這個偵測的錯誤是不能完全信賴 isNaN 的理由 +isNaN("blabla") // true: "blabla" 被轉換為數字,將其解析為數字失敗後回傳了 NaN +</pre> + +<h3 id="實用的特殊狀況行為">實用的特殊狀況行為</h3> + +<p>當然,你能以更用途導向的方法去思考 <code>isNaN()</code>:如果 <code>isNaN()</code> 回傳 <code>false</code>,那麼把 <code>x</code> 用在任何算術表達式都不會回傳 <code>NaN</code>。相反地,如果回傳 <code>true</code>,那麼把 <code>x</code> 用在任何算術表達式都會是 <code>NaN</code>。這在 JavaScript 的意義是 <code>isNaN(x) == true</code> 等於 <code>x - 0</code> 回傳 <code>NaN</code>(儘管在 JavaScript 裡面 <code>x - 0 == NaN</code> 永遠回傳 false,你因而無法測試)──事實上,<code>isNaN(x)</code>、<code>isNaN(x - 0)</code>、<code>isNaN(Number(x))</code>、<code>Number.isNaN(x - 0)</code>、<code>Number.isNaN(Number(x))</code> 在 JavaScript 裡面,都會回傳一樣的東西。而 <code>isNaN(x)</code> 是所有表達式裡面最短的一種。</p> + +<p>比方說,你可以用這個式子,去測試函式的參數能不能透過算術處理(也就是能「像」數字一樣被利用)、否則就提供預設值之類的。你可以透過上下文的根據以隱式數值轉換(implicitly converting values),以使用 JavaScript 提供的全部功能。</p> + +<h2 id="範例_2">範例</h2> + +<pre class="brush: js">function increment(x) { + if (isNaN(x)) x = 0; + return x + 1; +}; + +// 與 Number.isNaN() 一樣: +function increment(x) { + if (Number.isNaN(Number(x))) x = 0; + return x + 1; +}; + +// 以下範例的函式參數 x,isNaN(x) 都會回傳 false, +// 儘管 x 不是數字,依舊能用在算術表達式。 +increment(""); // 1: "" 被轉換成 0 +increment(new String()); // 1: 空字串的新字串物件被轉換成 0 +increment([]); // 1: [] 被轉換成 0 +increment(new Array()); // 1: 空陣列的新陣列物件被轉換成 0 +increment("0"); // 1: "0" 被轉換成 0 +increment("1"); // 2: "1" 被轉換成 1 +increment("0.1"); // 1.1: "0.1" 被轉換成 0.1 +increment("Infinity"); // Infinity: "Infinity" 被轉換成 Infinity +increment(null); // 1: null 被轉換成 0 +increment(false); // 1: false 被轉換成 0 +increment(true); // 2: true 被轉換成 1 +increment(new Date()); // 回傳以毫秒為單位加 1,當今的日期/時間 + +// 以下範例的函式參數 x,isNaN(x) 都會回傳 false,而 x 的確是數字。 +increment(-1); // 0 +increment(-0.1); // 0.9 +increment(0); // 1 +increment(1); // 2 +increment(2); // 3 +// …等等… +increment(Infinity); // Infinity + +// 以下範例的函式參數 x,isNaN(x) 都會回傳 true,x 也的確不是數字。 +// 使得函式會被 0 取代,並回傳 1 +increment(String); // 1 +increment(Array); // 1 +increment("blabla"); // 1 +increment("-blabla"); // 1 +increment(0/0); // 1 +increment("0/0"); // 1 +increment(Infinity/Infinity); // 1 +increment(NaN); // 1 +increment(undefined); // 1 +increment(); // 1 + +// isNaN(x) 與 isNaN(Number(x)) 永遠一樣,不過這裡的 x 是強制存在的! +isNaN(x) == isNaN(Number(x)) // 針對所有 x 的值都是 true,x == undefined 也不例外, + // 因為 isNaN(undefined) == true 且 Number(undefined) 回傳 NaN, + // 不過…… +isNaN() == isNaN(Number()) // false,因為 isNaN() == true 且 Number() == 0 +</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('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.1.2.4', 'isNaN')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-isnan-number', 'isNaN')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-isnan-number', 'isNaN')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + + + +<p>{{Compat("javascript.builtins.isNaN")}}</p> + +<h2 id="參見">參見</h2> + +<ul> + <li>{{jsxref("NaN")}}</li> + <li>{{jsxref("Number.isNaN()")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/json/index.html b/files/zh-tw/web/javascript/reference/global_objects/json/index.html new file mode 100644 index 0000000000..8d3aeadbf2 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/json/index.html @@ -0,0 +1,206 @@ +--- +title: JSON +slug: Web/JavaScript/Reference/Global_Objects/JSON +tags: + - JSON + - JavaScript + - NeedsTranslation + - Object + - Reference + - Référence(2) + - TopicStub + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/JSON +--- +<div>{{JSRef}}</div> + +<p><strong><code>JSON</code></strong> 物件包含了解析、或是轉換為 <a class="external" href="http://json.org/">JavaScript Object Notation</a>({{glossary("JSON")}})格式的方法。這物件不能被呼叫或建構;而除了它的兩個方法屬性以外,本身也沒有特別的功能。</p> + +<h2 id="描述">描述</h2> + +<h3 id="JavaScript_Object_Notation">JavaScript Object Notation</h3> + +<p>JSON 是序列物件、陣列、數字、字串、布林值、還有 {{jsxref("null")}} 的語法。它建基、但不同於 JavaScript:有些 JavaScript 不是 JSON、而有些 JSON 不是 JavaScript。請參見 <a href="http://timelessrepo.com/json-isnt-a-javascript-subset">JSON: The JavaScript subset that isn't</a>。</p> + +<table> + <caption>JavaScript 與 JSON 的差別</caption> + <thead> + <tr> + <th scope="col">JavaScript 型別</th> + <th scope="col">與 JSON 的差別</th> + </tr> + </thead> + <tbody> + <tr> + <td>物件與陣列</td> + <td>屬性名稱必須是包含在雙引號中的字串;禁止尾後逗號。</td> + </tr> + <tr> + <td>數字</td> + <td>數字不可以0作為開頭(在 JSON.stringify 0會被忽略,但是在 JSON.parse 會造成語法錯誤);小數點前面必須至少有一位數字。</td> + </tr> + <tr> + <td>字串</td> + <td> + <p>Only a limited set of characters may be escaped; certain control characters are prohibited; the Unicode line separator (<a href="http://unicode-table.com/en/2028/">U+2028</a>) and paragraph separator (<a href="http://unicode-table.com/en/2029/">U+2029</a>) characters are permitted; strings must be double-quoted. See the following example where {{jsxref("JSON.parse()")}} works fine and a {{jsxref("SyntaxError")}} is thrown when evaluating the code as JavaScript:</p> + + <pre class="brush: js"> +var code = '"\u2028\u2029"'; +JSON.parse(code); // works fine +eval(code); // fails +</pre> + </td> + </tr> + </tbody> +</table> + +<p>JSON 的完整語法如下:</p> + +<pre><var>JSON</var> = <strong>null</strong> + <em>or</em> <strong>true</strong> <em>or</em> <strong>false</strong> + <em>or</em> <var>JSONNumber</var> + <em>or</em> <var>JSONString</var> + <em>or</em> <var>JSONObject</var> + <em>or</em> <var>JSONArray</var> + +<var>JSONNumber</var> = <strong>-</strong> <var>PositiveNumber</var> + <em>or</em> <var>PositiveNumber</var> +<var>PositiveNumber</var> = DecimalNumber + <em>or</em> <var>DecimalNumber</var> <strong>.</strong> <var>Digits</var> + <em>or</em> <var>DecimalNumber</var> <strong>.</strong> <var>Digits</var> <var>ExponentPart</var> + <em>or</em> <var>DecimalNumber</var> <var>ExponentPart</var> +<var>DecimalNumber</var> = <strong>0</strong> + <em>or</em> <var>OneToNine</var> <var>Digits</var> +<var>ExponentPart</var> = <strong>e</strong> <var>Exponent</var> + <em>or</em> <strong>E</strong> <var>Exponent</var> +<var>Exponent</var> = <var>Digits</var> + <em>or</em> <strong>+</strong> <var>Digits</var> + <em>or</em> <strong>-</strong> <var>Digits</var> +<var>Digits</var> = <var>Digit</var> + <em>or</em> <var>Digits</var> <var>Digit</var> +<var>Digit</var> = <strong>0</strong> through <strong>9</strong> +<var>OneToNine</var> = <strong>1</strong> through <strong>9</strong> + +<var>JSONString</var> = <strong>""</strong> + <em>or</em> <strong>"</strong> <var>StringCharacters</var> <strong>"</strong> +<var>StringCharacters</var> = <var>StringCharacter</var> + <em>or</em> <var>StringCharacters</var> <var>StringCharacter</var> +<var>StringCharacter</var> = any character + <em>except</em> <strong>"</strong> <em>or</em> <strong>\</strong> <em>or</em> U+0000 through U+001F + <em>or</em> <var>EscapeSequence</var> +<var>EscapeSequence</var> = <strong>\"</strong> <em>or</em> <strong>\/</strong> <em>or</em> <strong>\\</strong> <em>or</em> <strong>\b</strong> <em>or</em> <strong>\f</strong> <em>or</em> <strong>\n</strong> <em>or</em> <strong>\r</strong> <em>or</em> <strong>\t</strong> + <em>or</em> <strong>\u</strong> <var>HexDigit</var> <var>HexDigit</var> <var>HexDigit</var> <var>HexDigit</var> +<var>HexDigit</var> = <strong>0</strong> through <strong>9</strong> + <em>or</em> <strong>A</strong> through <strong>F</strong> + <em>or</em> <strong>a</strong> through <strong>f</strong> + +<var>JSONObject</var> = <strong>{</strong> <strong>}</strong> + <em>or</em> <strong>{</strong> <var>Members</var> <strong>}</strong> +<var>Members</var> = <var>JSONString</var> <strong>:</strong> <var>JSON</var> + <em>or</em> <var>Members</var> <strong>,</strong> <var>JSONString</var> <strong>:</strong> <var>JSON</var> + +<var>JSONArray</var> = <strong>[</strong> <strong>]</strong> + <em>or</em> <strong>[</strong> <var>ArrayElements</var> <strong>]</strong> +<var>ArrayElements</var> = <var>JSON</var> + <em>or</em> <var>ArrayElements</var> <strong>,</strong> <var>JSON</var> +</pre> + +<p>Insignificant whitespace may be present anywhere except within a <code><var>JSONNumber</var></code> (numbers must contain no whitespace) or <code><var>JSONString</var></code> (where it is interpreted as the corresponding character in the string, or would cause an error). The tab character (<a href="http://unicode-table.com/en/0009/">U+0009</a>), carriage return (<a href="http://unicode-table.com/en/000D/">U+000D</a>), line feed (<a href="http://unicode-table.com/en/000A/">U+000A</a>), and space (<a href="http://unicode-table.com/en/0020/">U+0020</a>) characters are the only valid whitespace characters.</p> + +<h2 id="方法">方法</h2> + +<dl> + <dt>{{jsxref("JSON.parse()")}}</dt> + <dd>解析 JSON 字串,能改變給定值和屬性、接著回傳解析值。</dd> + <dt>{{jsxref("JSON.stringify()")}}</dt> + <dd>回傳給定的 JSON 對應字串,可自行決定只想包括哪些特定屬性、或替換的屬性值。</dd> +</dl> + +<h2 id="Polyfill">Polyfill</h2> + +<p>舊版瀏覽器並不支援 <code>JSON</code>。你可以在程式碼開頭插入以下程式碼,以解決這個問題。這個程式碼能實做不支援原生 <code>JSON</code> 物件的瀏覽器(如 Internet Explorer 6)。</p> + +<p>以下演算法能仿製原生 <code>JSON</code> 物件。</p> + +<pre class="brush: js">if (!window.JSON) { + window.JSON = { + parse: function(sJSON) { return eval('(' + sJSON + ')'); }, + stringify: (function () { + var toString = Object.prototype.toString; + var hasOwnProperty = Object.prototype.hasOwnProperty; + var isArray = Array.isArray || function (a) { return toString.call(a) === '[object Array]'; }; + var escMap = {'"': '\\"', '\\': '\\\\', '\b': '\\b', '\f': '\\f', '\n': '\\n', '\r': '\\r', '\t': '\\t'}; + var escFunc = function (m) { return escMap[m] || '\\u' + (m.charCodeAt(0) + 0x10000).toString(16).substr(1); }; + var escRE = /[\\"\u0000-\u001F\u2028\u2029]/g; + return function stringify(value) { + if (value == null) { + return 'null'; + } else if (typeof value === 'number') { + return isFinite(value) ? value.toString() : 'null'; + } else if (typeof value === 'boolean') { + return value.toString(); + } else if (typeof value === 'object') { + if (typeof value.toJSON === 'function') { + return stringify(value.toJSON()); + } else if (isArray(value)) { + var res = '['; + for (var i = 0; i < value.length; i++) + res += (i ? ', ' : '') + stringify(value[i]); + return res + ']'; + } else if (toString.call(value) === '[object Object]') { + var tmp = []; + for (var k in value) { + // in case "hasOwnProperty" has been shadowed + if (hasOwnProperty.call(value, k)) + tmp.push(stringify(k) + ': ' + stringify(value[k])); + } + return '{' + tmp.join(', ') + '}'; + } + } + return '"' + value.toString().replace(escRE, escFunc) + '"'; + }; + })() + }; +} +</pre> + +<p>More complex well-known <a class="external" href="http://remysharp.com/2010/10/08/what-is-a-polyfill/">polyfills</a> for the <code>JSON</code> object are <a class="link-https" href="https://github.com/douglascrockford/JSON-js">JSON2</a> and <a class="external" href="http://bestiejs.github.com/json3">JSON3</a>.</p> + +<h2 id="規範">規範</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.12', 'JSON')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-json-object', 'JSON')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-json-object', 'JSON')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + + + +<div>{{Compat("javascript.builtins.JSON")}}</div> + +<h2 id="參見">參見</h2> + +<ul> + <li>{{jsxref("Date.prototype.toJSON()")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/json/parse/index.html b/files/zh-tw/web/javascript/reference/global_objects/json/parse/index.html new file mode 100644 index 0000000000..eb821587a5 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/json/parse/index.html @@ -0,0 +1,170 @@ +--- +title: JSON.parse() +slug: Web/JavaScript/Reference/Global_Objects/JSON/parse +translation_of: Web/JavaScript/Reference/Global_Objects/JSON/parse +--- +<div>{{JSRef}}</div> + +<p><strong><code>JSON.parse()</code></strong> 方法把會把一個JSON字串轉換成 JavaScript的數值或是物件。另外也可選擇使用reviver函數讓這些數值或是物件在被回傳之前做轉換。</p> + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox">JSON.parse(<var>text</var>[, <var>reviver</var>])</pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>text</code></dt> + <dd>要解析成 JSON 的字串。針對 JSON 語法的描述,請參見 {{jsxref("JSON")}} 物件。</dd> + <dt><code>reviver</code> {{optional_inline}}</dt> + <dd>為選擇性的參數,用來描述JSON字串中的值該如何被解析並回傳的函式(function)</dd> +</dl> + +<h3 id="回傳值">回傳值</h3> + +<p>從給定的 JSON <code>text</code> 回傳對應的 {{jsxref("Object")}}。</p> + +<h3 id="Throws">Throws</h3> + +<p>如果解析的字串不是合法的JSON格式會丟出一個 {{jsxref("SyntaxError")}} 例外</p> + +<h2 id="範例">範例</h2> + +<h3 id="Using_JSON.parse">Using <code>JSON.parse()</code></h3> + +<pre class="brush: js">JSON.parse('{}'); // {} +JSON.parse('true'); // true +JSON.parse('"foo"'); // "foo" +JSON.parse('[1, 5, "false"]'); // [1, 5, "false"] +JSON.parse('null'); // null +</pre> + +<h3 id="使用_reviver_參數">使用 <strong><code>reviver</code></strong> 參數</h3> + +<p><code><font face="Open Sans, Arial, sans-serif">如果</font>reviver函數有被指定</code>,字串解析後產生出來的值會在函式回傳前經過轉換。 具體來講,解析後的值或是物件屬性會一個接一個地被這個reviver函數過濾(順序是由巢狀架構中最深的到最淺的),而當一個屬性即將被過濾時,該屬性的名稱(字串形態)以及值會被當作參數傳入reviver函數。如果reviver函數回傳了 {{jsxref("undefined")}} (或是沒有回傳值, 例如:函式提早結束),則該屬性會從物件中被刪除;反之如果成功的話,該屬性的值就會被新的回傳值取代。</p> + +<p>如果reviver只需轉換某些特定的值,請記得將其他不須特別轉換的值以原來的值回傳,否則這些值會從回傳的結果物件中刪除。</p> + +<pre class="brush: js">JSON.parse('{"p": 5}', function(k, v) { + if (typeof v === 'number') { + return v * 2; // return v * 2 for numbers + } + return v; // return everything else unchanged +}); + +// { p: 10 } + +JSON.parse('{"1": 1, "2": 2, "3": {"4": 4, "5": {"6": 6}}}', function(k, v) { + console.log(k); // log the current property name, the last is "". + return v; // return the unchanged property value. +}); + +// 1 +// 2 +// 4 +// 6 +// 5 +// 3 +// "" +</pre> + +<h3 id="JSON.parse_不容許尾部有逗號"><code>JSON.parse()</code> 不容許尾部有逗號</h3> + +<pre class="example-bad brush: js example-bad">// 這兩個都會拋出 SyntaxError +JSON.parse('[1, 2, 3, 4, ]'); +JSON.parse('{"foo" : 1, }'); +</pre> + +<h2 id="規範">規範</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">規範</th> + <th scope="col">狀態</th> + <th scope="col">註解</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.12.2', 'JSON.parse')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>初始定義。從 JavaScript 1.7 導入。</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-json.parse', 'JSON.parse')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-json.parse', 'JSON.parse')}}</td> + <td>{{Spec2('ESDraft')}}</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>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>基本功能</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("1.9.1")}}</td> + <td>{{CompatIE("8.0")}}</td> + <td>{{CompatOpera("10.5")}}</td> + <td>{{CompatSafari("4.0")}}</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>{{CompatGeckoMobile("1.0")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Gecko相關">Gecko相關</h2> + +<p>從Gecko 29版本開始{{geckoRelease("29")}},錯誤格式的JSON字串會產生更詳細的錯誤訊息,包含造成解析錯誤的行數及列數。這在針對大量JSON資料進行除錯時會很有幫助。</p> + +<pre class="brush: js">JSON.parse('[1, 2, 3, 4,]'); +// SyntaxError: JSON.parse: unexpected character at +// line 1 column 13 of the JSON data +</pre> + +<h2 id="參見">參見</h2> + +<ul> + <li>{{jsxref("JSON.stringify()")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/json/stringify/index.html b/files/zh-tw/web/javascript/reference/global_objects/json/stringify/index.html new file mode 100644 index 0000000000..5169d7d748 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/json/stringify/index.html @@ -0,0 +1,280 @@ +--- +title: JSON.stringify() +slug: Web/JavaScript/Reference/Global_Objects/JSON/stringify +translation_of: Web/JavaScript/Reference/Global_Objects/JSON/stringify +--- +<div>{{JSRef}}</div> + +<p><strong><code>JSON.stringify()</code></strong> method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified, or optionally including only the specified properties if a replacer array is specified.</p> + +<div>{{EmbedInteractiveExample("pages/js/json-stringify.html")}}</div> + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox"><code>JSON.stringify(<var>value</var>[, <var>replacer</var>[, <var>space</var>]])</code></pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>value</code></dt> + <dd>The value to convert to a JSON string.</dd> + <dt><code>replacer</code> {{optional_inline}}</dt> + <dd>A function that alters the behavior of the stringification process, or an array of {{jsxref("String")}} and {{jsxref("Number")}} objects that serve as a whitelist for selecting/filtering the properties of the value object to be included in the JSON string. If this value is null or not provided, all properties of the object are included in the resulting JSON string.</dd> + <dt><code>space</code> {{optional_inline}}</dt> + <dd>A {{jsxref("String")}} or {{jsxref("Number")}} object that's used to insert white space into the output JSON string for readability purposes. If this is a <code>Number</code>, it indicates the number of space characters to use as white space; this number is capped at 10 (if it is greater, the value is just 10). Values less than 1 indicate that no space should be used. If this is a <code>String</code>, the string (or the first 10 characters of the string, if it's longer than that) is used as white space. If this parameter is not provided (or is null), no white space is used.</dd> +</dl> + +<h3 id="回傳值">回傳值</h3> + +<p>A JSON string representing the given value.</p> + +<h2 id="Description">Description</h2> + +<p><code>JSON.stringify()</code> converts a value to JSON notation representing it:</p> + +<ul> + <li>{{jsxref("Boolean")}}, {{jsxref("Number")}}, and {{jsxref("String")}} objects are converted to the corresponding primitive values during stringification, in accord with the traditional conversion semantics.</li> + <li>If {{jsxref("undefined")}}, a function, or a symbol is encountered during conversion it is either omitted (when it is found in an object) or censored to {{jsxref("null")}} (when it is found in an array). <code>JSON.stringify</code> can also just return <code>undefined</code> when passing in "pure" values like <code>JSON.stringify(function(){})</code> or <code>JSON.stringify(undefined)</code>.</li> + <li>All symbol-keyed properties will be completely ignored, even when using the <code>replacer</code> function.</li> + <li>Non-enumerable properties will be ignored</li> +</ul> + +<pre class="brush: js">JSON.stringify({}); // '{}' +JSON.stringify(true); // 'true' +JSON.stringify('foo'); // '"foo"' +JSON.stringify([1, 'false', false]); // '[1,"false",false]' +JSON.stringify({ x: 5 }); // '{"x":5}' + +JSON.stringify(new Date(2006, 0, 2, 15, 4, 5)) +// '"2006-01-02T15:04:05.000Z"' + +JSON.stringify({ x: 5, y: 6 }); +// '{"x":5,"y":6}' +JSON.stringify([new Number(3), new String('false'), new Boolean(false)]); +// '[3,"false",false]' + +JSON.stringify({ x: [10, undefined, function(){}, Symbol('')] }); +// '{"x":[10,null,null,null]}' + +// Symbols: +JSON.stringify({ x: undefined, y: Object, z: Symbol('') }); +// '{}' +JSON.stringify({ [Symbol('foo')]: 'foo' }); +// '{}' +JSON.stringify({ [Symbol.for('foo')]: 'foo' }, [Symbol.for('foo')]); +// '{}' +JSON.stringify({ [Symbol.for('foo')]: 'foo' }, function(k, v) { + if (typeof k === 'symbol') { + return 'a symbol'; + } +}); +// '{}' + +// Non-enumerable properties: +JSON.stringify( Object.create(null, { x: { value: 'x', enumerable: false }, y: { value: 'y', enumerable: true } }) ); +// '{"y":"y"}' + +</pre> + +<h3 id="The_replacer_parameter"><a id="The replacer parameter" name="The replacer parameter"></a>The <code>replacer</code> parameter</h3> + +<p>The <code>replacer</code> parameter can be either a function or an array. As a function, it takes two parameters, the key and the value being stringified. The object in which the key was found is provided as the replacer's <code>this</code> parameter. Initially it gets called with an empty key representing the object being stringified, and it then gets called for each property on the object or array being stringified. It should return the value that should be added to the JSON string, as follows:</p> + +<ul> + <li>If you return a {{jsxref("Number")}}, the string corresponding to that number is used as the value for the property when added to the JSON string.</li> + <li>If you return a {{jsxref("String")}}, that string is used as the property's value when adding it to the JSON string.</li> + <li>If you return a {{jsxref("Boolean")}}, "true" or "false" is used as the property's value, as appropriate, when adding it to the JSON string.</li> + <li>If you return any other object, the object is recursively stringified into the JSON string, calling the <code>replacer</code> function on each property, unless the object is a function, in which case nothing is added to the JSON string.</li> + <li>If you return <code>undefined</code>, the property is not included (i.e., filtered out) in the output JSON string.</li> +</ul> + +<div class="note"><strong>Note:</strong> You cannot use the <code>replacer</code> function to remove values from an array. If you return <code>undefined</code> or a function then <code>null</code> is used instead.</div> + +<h4 id="Example_with_a_function">Example with a function</h4> + +<pre class="brush: js">function replacer(key, value) { + // Filtering out properties + if (typeof value === 'string') { + return undefined; + } + return value; +} + +var foo = {foundation: 'Mozilla', model: 'box', week: 45, transport: 'car', month: 7}; +JSON.stringify(foo, replacer); +// '{"week":45,"month":7}' +</pre> + +<h4 id="Example_with_an_array">Example with an array</h4> + +<p>If <code>replacer</code> is an array, the array's values indicate the names of the properties in the object that should be included in the resulting JSON string.</p> + +<pre class="brush: js">JSON.stringify(foo, ['week', 'month']); +// '{"week":45,"month":7}', only keep "week" and "month" properties +</pre> + +<h3 id="The_space_argument"><a id="The space argument" name="The space argument"></a>The <code>space</code> argument</h3> + +<p>The <code>space</code> argument may be used to control spacing in the final string. If it is a number, successive levels in the stringification will each be indented by this many space characters (up to 10). If it is a string, successive levels will be indented by this string (or the first ten characters of it).</p> + +<pre class="brush: js">JSON.stringify({ a: 2 }, null, ' '); +// '{ +// "a": 2 +// }' +</pre> + +<p>Using a tab character mimics standard pretty-print appearance:</p> + +<pre class="brush: js">JSON.stringify({ uno: 1, dos: 2 }, null, '\t'); +// returns the string: +// '{ +// "uno": 1, +// "dos": 2 +// }' +</pre> + +<h3 id="toJSON_behavior"><code>toJSON()</code> behavior</h3> + +<p>If an object being stringified has a property named <code>toJSON</code> whose value is a function, then the <code>toJSON()</code> method customizes JSON stringification behavior: instead of the object being serialized, the value returned by the <code>toJSON()</code> method when called will be serialized. <code>JSON.stringify()</code> calls <code>toJSON</code> with one parameter:</p> + +<ul> + <li>if this object is a property value, the property name</li> + <li>if it is in an array, the index in the array, as a string</li> + <li>an empty string if <code>JSON.stringify()</code> was directly called on this object</li> +</ul> + +<p>For example:</p> + +<pre class="brush: js">const bonnie = { + name: 'Bonnie Washington', + age: 17, + class: 'Year 5 Wisdom', + isMonitor: false, + toJSON: function(key) { + // Clone object to prevent accidentally performing modification on the original object + const cloneObj = { ...this }; + + delete cloneObj.age; + delete cloneObj.isMonitor; + cloneObj.year = 5; + cloneObj.class = 'Wisdom'; + + if (key) { + cloneObj.code = key; + } + + return cloneObj; + } +} + +JSON.stringify(bonnie); +// Returns '{"name":"Bonnie Washington","class":"Wisdom","year":5}' + +const students = {bonnie}; +JSON.stringify(students); +// Returns '{"bonnie":{"name":"Bonnie Washington","class":"Wisdom","year":5,"code":"bonnie"}}' + +const monitorCandidate = [bonnie]; +JSON.stringify(monitorCandidate) +// Returns '[{"name":"Bonnie Washington","class":"Wisdom","year":5,"code":"0"}]'</pre> + +<h3 id="Issue_with_plain_JSON.stringify_for_use_as_JavaScript">Issue with plain <code>JSON.stringify</code> for use as JavaScript</h3> + +<p>Note that JSON is <a href="http://timelessrepo.com/json-isnt-a-javascript-subset">not a completely strict subset of JavaScript</a>, with two line terminators (Line separator and Paragraph separator) not needing to be escaped in JSON but needing to be escaped in JavaScript. Therefore, if the JSON is meant to be evaluated or directly utilized within <a href="https://en.wikipedia.org/wiki/JSONP">JSONP</a>, the following utility can be used:</p> + +<pre class="brush: js">function jsFriendlyJSONStringify (s) { + return JSON.stringify(s). + replace(/\u2028/g, '\\u2028'). + replace(/\u2029/g, '\\u2029'); +} + +var s = { + a: String.fromCharCode(0x2028), + b: String.fromCharCode(0x2029) +}; +try { + eval('(' + JSON.stringify(s) + ')'); +} catch (e) { + console.log(e); // "SyntaxError: unterminated string literal" +} + +// No need for a catch +eval('(' + jsFriendlyJSONStringify(s) + ')'); + +// console.log in Firefox unescapes the Unicode if +// logged to console, so we use alert +alert(jsFriendlyJSONStringify(s)); // {"a":"\u2028","b":"\u2029"}</pre> + +<h3 id="Example_of_using_JSON.stringify_with_localStorage">Example of using <code>JSON.stringify()</code> with <code>localStorage</code></h3> + +<p>In a case where you want to store an object created by your user and allowing it to be restored even after the browser has been closed, the following example is a model for the applicability of <code>JSON.stringify()</code>:</p> + +<div class="warning"> +<p>Functions are not a valid JSON data type so they will not work. However, they can be displayed if first converted to a string (e.g. in the replacer), via the function's toString method. Also, some objects like {{jsxref("Date")}} will be a string after {{jsxref("JSON.parse()")}}.</p> +</div> + +<pre class="brush: js">// Creating an example of JSON +var session = { + 'screens': [], + 'state': true +}; +session.screens.push({ 'name': 'screenA', 'width': 450, 'height': 250 }); +session.screens.push({ 'name': 'screenB', 'width': 650, 'height': 350 }); +session.screens.push({ 'name': 'screenC', 'width': 750, 'height': 120 }); +session.screens.push({ 'name': 'screenD', 'width': 250, 'height': 60 }); +session.screens.push({ 'name': 'screenE', 'width': 390, 'height': 120 }); +session.screens.push({ 'name': 'screenF', 'width': 1240, 'height': 650 }); + +// Converting the JSON string with JSON.stringify() +// then saving with localStorage in the name of session +localStorage.setItem('session', JSON.stringify(session)); + +// Example of how to transform the String generated through +// JSON.stringify() and saved in localStorage in JSON object again +var restoredSession = JSON.parse(localStorage.getItem('session')); + +// Now restoredSession variable contains the object that was saved +// in localStorage +console.log(restoredSession); +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.12.3', 'JSON.stringify')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.7.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-json.stringify', 'JSON.stringify')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-json.stringify', 'JSON.stringify')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("javascript.builtins.JSON.stringify")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("JSON.parse()")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/map/index.html b/files/zh-tw/web/javascript/reference/global_objects/map/index.html new file mode 100644 index 0000000000..07dc862188 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/map/index.html @@ -0,0 +1,265 @@ +--- +title: Map +slug: Web/JavaScript/Reference/Global_Objects/Map +tags: + - ECMAScript 2015 + - JavaScript + - Map +translation_of: Web/JavaScript/Reference/Global_Objects/Map +--- +<div>{{JSRef}}</div> + +<p><span class="seoSummary"><strong><code>Map</code></strong> 是保存了鍵值對(key-value pairs)的物件。</span>任何值(包括物件及{{Glossary("Primitive", "基本型別(primitive)值")}})都可以作為鍵或值。</p> + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox">new Map([<em>iterable</em>])</pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>iterable</code></dt> + <dd>為一個{{jsxref("Array", "陣列")}}或其他元素成鍵值對的<a href="/zh-TW/docs/Web/JavaScript/Guide/iterable">可迭代</a>物件(有兩個元素的陣列,例如 <code>[[ 1, 'one' ],[ 2, 'two' ]]</code>)。每一個鍵值對都會被加入至新的 <code>Map</code>;<code>null</code> 會被視為 <code>undefined</code>。</dd> +</dl> + +<h2 id="描述">描述</h2> + +<p>一個 <code>Map</code> 物件會根據元素的新增順序走訪自身的所有元素 — {{jsxref("Statements/for...of", "for...of")}} 迴圈會在每次迭代回傳一個 <code>[key, value]</code> 陣列。</p> + + + +<h3 id="鍵的相等性">鍵的相等性</h3> + +<p>鍵相等是基於 <a href="https://wiki.developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness#Same-value-zero_equality">SameValueZero</a> 的演算法:<code>NaN</code> 被認為與 <code>NaN</code> 相同(即使 <code>NaN !== NaN</code>)並且根據 <code>===</code> 運算符的語義,所有其他值都被認為相等。在目前的ECMAScript 規範中,<code>-0</code> 和 <code>+0</code> 被認為是相等的,儘管在早期的草案中並非如此。詳細的內容請參閱 {{anch("Browser compatibility")}} 表中的 "Value equality for -0 and 0"。</p> + +<h3 id="Object_及_Map_的比較">Object 及 Map 的比較</h3> + +<p>{{jsxref("Object")}} 和 <code>Map</code> 類似。兩者都允許你設置對應的鍵值對,檢索這些值,刪除鍵,並檢測是否有什麼存儲在鍵中。正因為如此(也因為沒有內置的替代品),<code>Object</code> 在歷史上一直被當作 <code>Map</code> 使用;然而在某些情況下,使用 <code>Map</code> 有一些重要的不同之處:</p> + +<ul> + <li><code>Object</code> 的鍵是 {{jsxref("String", "字串")}} 和 {{jsxref("Symbol", "Symbol")}},而它們在 <code>Map</code> 中可以是任意的資料型態,包括函數,對象以及原始的資料型態。</li> + <li>你可以使用 <code>size</code> 屬性輕鬆地獲得 <code>Map</code> 的大小,而 <code>Object</code> 中的屬性數量必須手動確認。</li> + <li><code>Map</code> 是可迭代(<a href="/en-US/docs/Web/JavaScript/Guide/iterable">iterable</a>)的,因此可以直接迭代,而在 <code>Object</code> 上迭代則需要以某種方式獲取其鍵並對其進行迭代。</li> + <li><code>Object</code> 有一個原型,所以如果不小心,映射中有一些默認鍵可能與鍵發生衝突。從 ES5 開始,這可以通過使用 <code>map = Object.create(null)</code> 來繞過這個問題,但是很少這樣做。</li> + <li>在涉及頻繁添加和刪除鍵值對的場景中,<code>Map</code> 可能表現得更好。</li> +</ul> + +<h2 id="屬性">屬性</h2> + +<dl> + <dt><code>Map.length</code></dt> + <dd><code>length</code>屬性的值為 0<br> + 要計算 <code>Map</code> 中有多少元素,可以使用 {{jsxref("Map.prototype.size")}}。</dd> + <dt>{{jsxref("Map.@@species", "get Map[@@species]")}}</dt> + <dd>用於創建派生物件的構造函數。</dd> + <dt>{{jsxref("Map.prototype")}}</dt> + <dd>表示 <code>Map</code> 構造函數的原型,允許對所有的 <code>Map</code> 物件添加屬性</dd> +</dl> + +<h2 id="Map_物件實體"><code>Map</code> 物件實體</h2> + +<p>所有的 <code>Map</code> 實例都繼承自 {{jsxref("Map.prototype")}}.</p> + +<h3 id="屬性_2">屬性</h3> + +<p>{{page('zh-TW/Web/JavaScript/Reference/Global_Objects/Map/prototype','Properties')}}</p> + +<h3 id="方法">方法</h3> + +<p>{{page('zh-TW/Web/JavaScript/Reference/Global_Objects/Map/prototype','Methods')}}</p> + +<h2 id="範例">範例</h2> + +<h3 id="使用_Map_物件">使用 <code>Map</code> 物件</h3> + +<pre class="brush: js">var myMap = new Map(); + +var keyString = 'a string', + keyObj = {}, + keyFunc = function() {}; + +// setting the values +myMap.set(keyString, "value associated with 'a string'"); +myMap.set(keyObj, 'value associated with keyObj'); +myMap.set(keyFunc, 'value associated with keyFunc'); + +myMap.size; // 3 + +// getting the values +myMap.get(keyString); // "value associated with 'a string'" +myMap.get(keyObj); // "value associated with keyObj" +myMap.get(keyFunc); // "value associated with keyFunc" + +myMap.get('a string'); // "value associated with 'a string'" + // because keyString === 'a string' +myMap.get({}); // undefined, because keyObj !== {} +myMap.get(function() {}) // undefined, because keyFunc !== function () {} +</pre> + +<h3 id="使用_NaN_作為_Map_的鍵">使用 <code>NaN</code> 作為 <code>Map</code> 的鍵</h3> + +<p><code>NaN</code> 同樣可以作為 <code>Map</code> 的 key,雖然每個 <code>NaN</code> 都不等於自己本身,下面的例子是有效的,因為 <code>NaN</code> 無法區分彼此。</p> + +<pre class="brush: js">var myMap = new Map(); +myMap.set(NaN, 'not a number'); + +myMap.get(NaN); // "not a number" + +var otherNaN = Number('foo'); +myMap.get(otherNaN); // "not a number" +</pre> + +<h3 id="透過_for..of_迭代_Map">透過 <code>for..of</code> 迭代 <code>Map</code></h3> + +<p>Map 可以使用 <code>for..of</code> 迴圈進行迭代:</p> + +<pre class="brush: js">var myMap = new Map(); +myMap.set(0, 'zero'); +myMap.set(1, 'one'); +for (var [key, value] of myMap) { + console.log(key + ' = ' + value); +} +// 0 = zero +// 1 = one + +for (var key of myMap.keys()) { + console.log(key); +} +// 0 +// 1 + +for (var value of myMap.values()) { + console.log(value); +} +// zero +// one + +for (var [key, value] of myMap.entries()) { + console.log(key + ' = ' + value); +} +// 0 = zero +// 1 = one +</pre> + +<h3 id="透過_forEach_迭代_Map">透過 <code>forEach()</code> 迭代 <code>Map</code></h3> + +<p><code>Map</code> 可以使用 <code>forEach()</code> 方法進行迭代:</p> + +<pre class="brush: js">myMap.forEach(function(value, key) { + console.log(key + ' = ' + value); +}); +// Will show 2 logs; first with "0 = zero" and second with "1 = one" +</pre> + +<h3 id="與_Array_物件關聯">與 <code>Array</code> 物件關聯</h3> + +<pre class="brush: js">var kvArray = [['key1', 'value1'], ['key2', 'value2']]; + +// Use the regular Map constructor to transform a 2D key-value Array into a map +var myMap = new Map(kvArray); + +myMap.get('key1'); // returns "value1" + +// Use the Array.from function to transform a map into a 2D key-value Array +console.log(Array.from(myMap)); // Will show you exactly the same Array as kvArray + +// Or use the keys or values iterators and convert them to an array +console.log(Array.from(myMap.keys())); // Will show ["key1", "key2"] +</pre> + + + +<h3 id="複製與合併_Map"> 複製與合併 <code>Map</code></h3> + +<p>就像 <code>Array</code> 一樣,<code>Map</code> 可以被複製:</p> + +<pre><code>var original = new Map([ + [1, 'one'] +]); + +var clone = new Map(original); + +console.log(clone.get(1)); // one +console.log(original === clone); // false. Useful for shallow comparison</code></pre> + +<p>請記住,數據本身並非克隆的。</p> + +<p><code>Map</code> 可以被合併,保持鍵的唯一性:</p> + +<pre><code>var first = new Map([ + [1, 'one'], + [2, 'two'], + [3, 'three'], +]); + +var second = new Map([ + [1, 'uno'], + [2, 'dos'] +]); + +// Merge two maps. The last repeated key wins. +// Spread operator essentially converts a Map to an Array +var merged = new Map([...first, ...second]); + +console.log(merged.get(1)); // uno +console.log(merged.get(2)); // dos +console.log(merged.get(3)); // three</code></pre> + +<p><code>Map</code> 也可以跟 <code>Array</code> 合併:</p> + +<pre><code>var first = new Map([ + [1, 'one'], + [2, 'two'], + [3, 'three'], +]); + +var second = new Map([ + [1, 'uno'], + [2, 'dos'] +]); + +// Merge maps with an array. The last repeated key wins. +var merged = new Map([...first, ...second, [1, 'eins']]); + +console.log(merged.get(1)); // eins +console.log(merged.get(2)); // dos +console.log(merged.get(3)); // three</code> +</pre> + +<h2 id="規範">規範</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-map-objects', 'Map')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-map-objects', 'Map')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + + + +<p>{{Compat("javascript.builtins.Map")}}</p> + +<h2 id="參見">參見</h2> + +<ul> + <li><a class="link-https" href="https://bugzilla.mozilla.org/show_bug.cgi?id=697479">Map and Set bug at Mozilla</a></li> + <li><a class="external" href="http://wiki.ecmascript.org/doku.php?id=harmony:simple_maps_and_sets">ECMAScript Harmony proposal</a></li> + <li>{{jsxref("Set")}}</li> + <li>{{jsxref("WeakMap")}}</li> + <li>{{jsxref("WeakSet")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/math/abs/index.html b/files/zh-tw/web/javascript/reference/global_objects/math/abs/index.html new file mode 100644 index 0000000000..91be97bc11 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/math/abs/index.html @@ -0,0 +1,104 @@ +--- +title: Math.abs() +slug: Web/JavaScript/Reference/Global_Objects/Math/abs +tags: + - JavaScript + - Math + - Method + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Math/abs +--- +<div>{{JSRef}}</div> + +<p><strong><code>Math.abs()</code></strong> 函式會回傳一個數字的絕對值,即為:</p> + +<p><math display="block"><semantics><mrow><mstyle mathvariant="monospace"><mrow><mo lspace="0em" rspace="thinmathspace">Math.abs</mo><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo></mrow></mstyle><mo>=</mo><mrow><mo stretchy="false">|</mo><mi>x</mi><mo stretchy="false">|</mo></mrow><mo>=</mo><mrow><mo>{</mo><mtable columnalign="left left"><mtr><mtd><mi>x</mi></mtd><mtd><mtext>if</mtext><mspace width="1em"></mspace><mi>x</mi><mo>></mo><mn>0</mn></mtd></mtr><mtr><mtd><mi>0</mi></mtd><mtd><mtext>if</mtext><mspace width="1em"></mspace><mi>x</mi><mo>=</mo><mn>0</mn></mtd></mtr><mtr><mtd><mo>-</mo><mi>x</mi></mtd><mtd><mtext>if</mtext><mspace width="1em"></mspace><mi>x</mi><mo><</mo><mn>0</mn></mtd></mtr></mtable></mrow></mrow><annotation encoding="TeX">{\mathtt{\operatorname{Math.abs}(x)}} = {|x|} = \begin{cases} x & \text{if} \quad x \geq 0 \\ x & \text{if} \quad x < 0 \end{cases} </annotation></semantics></math></p> + +<div>{{EmbedInteractiveExample("pages/js/math-abs.html")}}</div> + + + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox">Math.abs(<var>x</var>)</pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>x</code></dt> + <dd>一個數字。</dd> +</dl> + +<h3 id="回傳值">回傳值</h3> + +<p>給定數字的絕對值。</p> + +<h2 id="描述">描述</h2> + +<p>Because <code>abs()</code> is a static method of <code>Math</code>, you always use it as <code>Math.abs()</code>, rather than as a method of a <code>Math</code> object you created (<code>Math</code> is not a constructor).</p> + +<h2 id="範例">範例</h2> + +<h3 id="Math.abs()_的行為"><code>Math.abs()</code> 的行為</h3> + +<p>Passing an empty object, an array with more than one member, a non-numeric string or {{jsxref("undefined")}}/empty variable returns {{jsxref("NaN")}}. Passing {{jsxref("null")}}, an empty string or an empty array returns 0.</p> + +<pre class="brush: js" dir="rtl">Math.abs('-1'); // 1 +Math.abs(-2); // 2 +Math.abs(null); // 0 +Math.abs(''); // 0 +Math.abs([]); // 0 +Math.abs([2]); // 2 +Math.abs([1,2]); // NaN +Math.abs({}); // NaN +Math.abs('string'); // NaN +Math.abs(); // NaN +</pre> + +<h2 id="規範">規範</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.8.2.1', 'Math.abs')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-math.abs', 'Math.abs')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-math.abs', 'Math.abs')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Math.abs")}}</p> + +<h2 id="參見">參見</h2> + +<ul> + <li>{{jsxref("Math.ceil()")}}</li> + <li>{{jsxref("Math.floor()")}}</li> + <li>{{jsxref("Math.round()")}}</li> + <li>{{jsxref("Math.sign()")}}</li> + <li>{{jsxref("Math.trunc()")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/math/ceil/index.html b/files/zh-tw/web/javascript/reference/global_objects/math/ceil/index.html new file mode 100644 index 0000000000..7ce7174f0b --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/math/ceil/index.html @@ -0,0 +1,170 @@ +--- +title: Math.ceil() +slug: Web/JavaScript/Reference/Global_Objects/Math/ceil +tags: + - JavaScript + - Math + - Method + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Math/ceil +--- +<div>{{JSRef}}</div> + +<p><strong><code>Math.ceil()</code></strong> 函式會回傳大於等於所給數字的最小整數。</p> + +<div>{{EmbedInteractiveExample("pages/js/math-ceil.html")}}</div> + + + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox"><code>Math.ceil(<var>x</var>)</code></pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>x</code></dt> + <dd>一個數字。</dd> +</dl> + +<h3 id="回傳值">回傳值</h3> + +<p>一個大於等於指定數字的最小整數。</p> + +<h2 id="描述">描述</h2> + +<p>Because <code>ceil()</code> is a static method of <code>Math</code>, you always use it as <code>Math.ceil()</code>, rather than as a method of a <code>Math</code> object you created (<code>Math</code> is not a constructor).</p> + +<h2 id="範例">範例</h2> + +<h3 id="使用_Math.ceil()">使用 <code>Math.ceil()</code></h3> + +<p>The following example shows example usage of <code>Math.ceil()</code>.</p> + +<pre class="brush: js">Math.ceil(.95); // 1 +Math.ceil(4); // 4 +Math.ceil(7.004); // 8 +Math.ceil(-0.95); // -0 +Math.ceil(-4); // -4 +Math.ceil(-7.004); // -7 +</pre> + +<h3 id="Decimal_adjustment">Decimal adjustment</h3> + +<pre class="brush: js">// Closure +(function() { + /** + * Decimal adjustment of a number. + * + * @param {String} type The type of adjustment. + * @param {Number} value The number. + * @param {Integer} exp The exponent (the 10 logarithm of the adjustment base). + * @returns {Number} The adjusted value. + */ + function decimalAdjust(type, value, exp) { + // If the exp is undefined or zero... + if (typeof exp === 'undefined' || +exp === 0) { + return Math[type](value); + } + value = +value; + exp = +exp; + // If the value is not a number or the exp is not an integer... + if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) { + return NaN; + } + // Shift + value = value.toString().split('e'); + value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp))); + // Shift back + value = value.toString().split('e'); + return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp)); + } + + // Decimal round + if (!Math.round10) { + Math.round10 = function(value, exp) { + return decimalAdjust('round', value, exp); + }; + } + // Decimal floor + if (!Math.floor10) { + Math.floor10 = function(value, exp) { + return decimalAdjust('floor', value, exp); + }; + } + // Decimal ceil + if (!Math.ceil10) { + Math.ceil10 = function(value, exp) { + return decimalAdjust('ceil', value, exp); + }; + } +})(); + +// Round +Math.round10(55.55, -1); // 55.6 +Math.round10(55.549, -1); // 55.5 +Math.round10(55, 1); // 60 +Math.round10(54.9, 1); // 50 +Math.round10(-55.55, -1); // -55.5 +Math.round10(-55.551, -1); // -55.6 +Math.round10(-55, 1); // -50 +Math.round10(-55.1, 1); // -60 +// Floor +Math.floor10(55.59, -1); // 55.5 +Math.floor10(59, 1); // 50 +Math.floor10(-55.51, -1); // -55.6 +Math.floor10(-51, 1); // -60 +// Ceil +Math.ceil10(55.51, -1); // 55.6 +Math.ceil10(51, 1); // 60 +Math.ceil10(-55.59, -1); // -55.5 +Math.ceil10(-59, 1); // -50 +</pre> + +<h2 id="規範">規範</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.8.2.6', 'Math.ceil')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-math.ceil', 'Math.ceil')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-math.ceil', 'Math.ceil')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Math.ceil")}}</p> + +<h2 id="參見">參見</h2> + +<ul> + <li>{{jsxref("Math.abs()")}}</li> + <li>{{jsxref("Math.floor()")}}</li> + <li>{{jsxref("Math.round()")}}</li> + <li>{{jsxref("Math.sign()")}}</li> + <li>{{jsxref("Math.trunc()")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/math/floor/index.html b/files/zh-tw/web/javascript/reference/global_objects/math/floor/index.html new file mode 100644 index 0000000000..5587d60838 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/math/floor/index.html @@ -0,0 +1,169 @@ +--- +title: Math.floor() +slug: Web/JavaScript/Reference/Global_Objects/Math/floor +tags: + - JavaScript + - Math + - Method + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Math/floor +--- +<div>{{JSRef}}</div> + +<p><strong><code>Math.floor()</code></strong> 函式會回傳小於等於所給數字的最大整數。</p> + +<div>{{EmbedInteractiveExample("pages/js/math-floor.html")}}</div> + + + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox"><code>Math.floor(<var>x</var>)</code></pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>x</code></dt> + <dd>數字型態。</dd> +</dl> + +<h3 id="回傳值">回傳值</h3> + +<p>小於等於所給數字的最大整數。</p> + +<h2 id="描述">描述</h2> + +<p> <code>floor()</code> 是 <code>Math</code>的靜態函式, 所以不需實體化<code>Math</code> 物件, 只要直接呼叫 <code>Math.floor()</code>就能使用。</p> + +<p>(此外<code>Math</code> 並不是建構子).</p> + +<h2 id="範例">範例</h2> + +<h3 id="使用_Math.floor">使用 <code>Math.floor()</code></h3> + +<pre class="brush: js">Math.floor( 45.95); // 45 +Math.floor( 45.05); // 45 +Math.floor( 4 ); // 4 +Math.floor(-45.05); // -46 +Math.floor(-45.95); // -46 +</pre> + +<h3 id="Decimal_adjustment">Decimal adjustment</h3> + +<pre class="brush: js">// Closure +(function() { + /** + * Decimal adjustment of a number. + * + * @param {String} type The type of adjustment. + * @param {Number} value The number. + * @param {Integer} exp The exponent (the 10 logarithm of the adjustment base). + * @returns {Number} The adjusted value. + */ + function decimalAdjust(type, value, exp) { + // If the exp is undefined or zero... + if (typeof exp === 'undefined' || +exp === 0) { + return Math[type](value); + } + value = +value; + exp = +exp; + // If the value is not a number or the exp is not an integer... + if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) { + return NaN; + } + // Shift + value = value.toString().split('e'); + value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp))); + // Shift back + value = value.toString().split('e'); + return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp)); + } + + // Decimal round + if (!Math.round10) { + Math.round10 = function(value, exp) { + return decimalAdjust('round', value, exp); + }; + } + // Decimal floor + if (!Math.floor10) { + Math.floor10 = function(value, exp) { + return decimalAdjust('floor', value, exp); + }; + } + // Decimal ceil + if (!Math.ceil10) { + Math.ceil10 = function(value, exp) { + return decimalAdjust('ceil', value, exp); + }; + } +})(); + +// Round +Math.round10(55.55, -1); // 55.6 +Math.round10(55.549, -1); // 55.5 +Math.round10(55, 1); // 60 +Math.round10(54.9, 1); // 50 +Math.round10(-55.55, -1); // -55.5 +Math.round10(-55.551, -1); // -55.6 +Math.round10(-55, 1); // -50 +Math.round10(-55.1, 1); // -60 +// Floor +Math.floor10(55.59, -1); // 55.5 +Math.floor10(59, 1); // 50 +Math.floor10(-55.51, -1); // -55.6 +Math.floor10(-51, 1); // -60 +// Ceil +Math.ceil10(55.51, -1); // 55.6 +Math.ceil10(51, 1); // 60 +Math.ceil10(-55.59, -1); // -55.5 +Math.ceil10(-59, 1); // -50 +</pre> + +<h2 id="規範">規範</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.8.2.9', 'Math.floor')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-math.floor', 'Math.floor')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-math.floor', 'Math.floor')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Math.floor")}}</p> + +<h2 id="參見">參見</h2> + +<ul> + <li>{{jsxref("Math.abs()")}}</li> + <li>{{jsxref("Math.ceil()")}}</li> + <li>{{jsxref("Math.round()")}}</li> + <li>{{jsxref("Math.sign()")}}</li> + <li>{{jsxref("Math.trunc()")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/math/index.html b/files/zh-tw/web/javascript/reference/global_objects/math/index.html new file mode 100644 index 0000000000..c67999150e --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/math/index.html @@ -0,0 +1,196 @@ +--- +title: Math +slug: Web/JavaScript/Reference/Global_Objects/Math +tags: + - JavaScript + - Math + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/Math +--- +<div>{{JSRef}}</div> + +<p><strong><code>Math</code></strong> 是一個擁有數學常數及數學函數(非函式物件)屬性及方法的內建物件。</p> + +<h2 id="描述">描述</h2> + +<p>不像其他的全域物件,<code>Math</code> 並非建構函式。所有 <code>Math</code> 的屬性及方法皆為靜態。你可以使用 <code>Math.PI</code> 來參考到圓周率 pi 的常數值,以及可以呼叫 <code>Math.sin(x)</code> 函式來計算三角函數正弦曲線 sine(<code>x</code> 為方法的引數)。常數是由 JavaScript 中實數的完整精度來定義。</p> + +<h2 id="屬性">屬性</h2> + +<dl> + <dt>{{jsxref("Math.E")}}</dt> + <dd>歐拉常數 (此指自然常數) ,也是自然對數的底數,約為2.718。</dd> + <dt>{{jsxref("Math.LN2")}}</dt> + <dd>2 的自然對數,約為0.693。</dd> + <dt>{{jsxref("Math.LN10")}}</dt> + <dd>10 的自然對數,約為2.303。</dd> + <dt>{{jsxref("Math.LOG2E")}}</dt> + <dd>以 2 為底的 E 的對數,約為1.443。</dd> + <dt>{{jsxref("Math.LOG10E")}}</dt> + <dd>以 10 為底的 E 的對數,約為0.434。</dd> + <dt>{{jsxref("Math.PI")}}</dt> + <dd>一個圓的圓周和其直徑比值,約為 3.14159。</dd> + <dt>{{jsxref("Math.SQRT1_2")}}</dt> + <dd>1/2的平方根;也就是1除以2的平方根,約為 0.707。</dd> + <dt>{{jsxref("Math.SQRT2")}}</dt> + <dd>2的平方根,約為 1.414。</dd> +</dl> + +<h2 id="方法">方法</h2> + +<div class="note"> +<p>注意三角函數 <span style="font-size: 1rem; letter-spacing: -0.00278rem;">(</span><code style="font-style: normal; letter-spacing: -0.00278rem;">sin()</code><span style="font-size: 1rem; letter-spacing: -0.00278rem;">, </span><code style="font-style: normal; letter-spacing: -0.00278rem;">cos()</code><span style="font-size: 1rem; letter-spacing: -0.00278rem;">, </span><code style="font-style: normal; letter-spacing: -0.00278rem;">tan()</code><span style="font-size: 1rem; letter-spacing: -0.00278rem;">, </span><code style="font-style: normal; letter-spacing: -0.00278rem;">asin()</code><span style="font-size: 1rem; letter-spacing: -0.00278rem;">, </span><code style="font-style: normal; letter-spacing: -0.00278rem;">acos()</code><span style="font-size: 1rem; letter-spacing: -0.00278rem;">, </span><code style="font-style: normal; letter-spacing: -0.00278rem;">atan()</code><span style="font-size: 1rem; letter-spacing: -0.00278rem;">, </span><code style="font-style: normal; letter-spacing: -0.00278rem;">atan2()</code><span style="font-size: 1rem; letter-spacing: -0.00278rem;">) 的參數或回傳值的角度皆以弧度為單位。把角度乘上 </span><code style="font-style: normal; letter-spacing: -0.00278rem;">(Math.PI / 180)</code> 會得到弧度單位,將弧度除以該數則會轉換回一般所用的角度單位。</p> +</div> + +<div class="note"> +<p>注意許多數學方法的精度是取決於實作方式的。這意味著不同的瀏覽器可能會得到不同的結果,甚至同一個 JS引擎在不同的作業系統或架構上所得到的結果都有可能相異。</p> +</div> + +<dl> + <dt>{{jsxref("Global_Objects/Math/abs", "Math.abs(x)")}}</dt> + <dd>回傳 x 的絕對值。</dd> + <dt>{{jsxref("Global_Objects/Math/acos", "Math.acos(x)")}}</dt> + <dd>回傳 x 的反餘弦值。</dd> + <dt>{{jsxref("Global_Objects/Math/acosh", "Math.acosh(x)")}}</dt> + <dd>Returns the hyperbolic arccosine of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/asin", "Math.asin(x)")}}</dt> + <dd>回傳 x 的反正弦值。</dd> + <dt>{{jsxref("Global_Objects/Math/asinh", "Math.asinh(x)")}}</dt> + <dd>Returns the hyperbolic arcsine of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/atan", "Math.atan(x)")}}</dt> + <dd>回傳 x 的反正切值。</dd> + <dt>{{jsxref("Global_Objects/Math/atanh", "Math.atanh(x)")}}</dt> + <dd>Returns the hyperbolic arctangent of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/atan2", "Math.atan2(y, x)")}}</dt> + <dd>Returns the arctangent of the quotient of its arguments.</dd> + <dt>{{jsxref("Global_Objects/Math/cbrt", "Math.cbrt(x)")}}</dt> + <dd>回傳 x 的立方根值。</dd> + <dt>{{jsxref("Global_Objects/Math/ceil", "Math.ceil(x)")}}</dt> + <dd>回傳不小於 x 的最小整數值。</dd> + <dt>{{jsxref("Global_Objects/Math/clz32", "Math.clz32(x)")}}</dt> + <dd>Returns the number of leading zeroes of a 32-bit integer.</dd> + <dt>{{jsxref("Global_Objects/Math/cos", "Math.cos(x)")}}</dt> + <dd>回傳 x 的餘弦值。</dd> + <dt>{{jsxref("Global_Objects/Math/cosh", "Math.cosh(x)")}}</dt> + <dd>Returns the hyperbolic cosine of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/exp", "Math.exp(x)")}}</dt> + <dd>回傳 E<sup>x</sup>,x 為給定數值,E 為歐拉常數 (自然對數的底數)。</dd> + <dt>{{jsxref("Global_Objects/Math/expm1", "Math.expm1(x)")}}</dt> + <dd>回傳 <code>exp(x)</code> 減去1的值。</dd> + <dt>{{jsxref("Global_Objects/Math/floor", "Math.floor(x)")}}</dt> + <dd>回傳不大於 x 的最大整數值。</dd> + <dt>{{jsxref("Global_Objects/Math/fround", "Math.fround(x)")}}</dt> + <dd>Returns the nearest <a href="http://en.wikipedia.org/wiki/Single-precision_floating-point_format" title="link to the wikipedia page on single precision">single precision</a> float representation of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/hypot", "Math.hypot([x[, y[, …]]])")}}</dt> + <dd>回傳參數平方之和的平方根。</dd> + <dt>{{jsxref("Global_Objects/Math/imul", "Math.imul(x, y)")}}</dt> + <dd>Returns the result of a 32-bit integer multiplication.</dd> + <dt>{{jsxref("Global_Objects/Math/log", "Math.log(x)")}}</dt> + <dd>回傳 x 的自然對數值。</dd> + <dt>{{jsxref("Global_Objects/Math/log1p", "Math.log1p(x)")}}</dt> + <dd>回傳 <code>1 + x</code> 的自然對數值。</dd> + <dt>{{jsxref("Global_Objects/Math/log10", "Math.log10(x)")}}</dt> + <dd>回傳以 10 為底,x 的對數值。</dd> + <dt>{{jsxref("Global_Objects/Math/log2", "Math.log2(x)")}}</dt> + <dd>回傳以 2 為底,x 的對數值。</dd> + <dt>{{jsxref("Global_Objects/Math/max", "Math.max([x[, y[, …]]])")}}</dt> + <dd>回傳給定數值中的最大值。</dd> + <dt>{{jsxref("Global_Objects/Math/min", "Math.min([x[, y[, …]]])")}}</dt> + <dd>回傳給定數值中的最小值。</dd> + <dt>{{jsxref("Global_Objects/Math/pow", "Math.pow(x, y)")}}</dt> + <dd>回傳 x 的 y 次方,也就是 <code>x<sup>y</sup></code>。</dd> + <dt>{{jsxref("Global_Objects/Math/random", "Math.random()")}}</dt> + <dd>回傳一個 0 到 1 之間的偽隨機值。</dd> + <dt>{{jsxref("Global_Objects/Math/round", "Math.round(x)")}}</dt> + <dd>回傳 x 的四捨五入值。</dd> + <dt>{{jsxref("Global_Objects/Math/sign", "Math.sign(x)")}}</dt> + <dd>回傳 x 的正負號,也就是回傳 x 的正負。</dd> + <dt>{{jsxref("Global_Objects/Math/sin", "Math.sin(x)")}}</dt> + <dd>回傳 x 的正弦值。</dd> + <dt>{{jsxref("Global_Objects/Math/sinh", "Math.sinh(x)")}}</dt> + <dd>Returns the hyperbolic sine of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/sqrt", "Math.sqrt(x)")}}</dt> + <dd>回傳 x 的正平方根。</dd> + <dt>{{jsxref("Global_Objects/Math/tan", "Math.tan(x)")}}</dt> + <dd>回傳 x 的正切值。</dd> + <dt>{{jsxref("Global_Objects/Math/tanh", "Math.tanh(x)")}}</dt> + <dd>Returns the hyperbolic tangent of a number.</dd> + <dt><code>Math.toSource()</code> {{non-standard_inline}}</dt> + <dd>回傳字串 <code>"Math"</code>。</dd> + <dt>{{jsxref("Global_Objects/Math/trunc", "Math.trunc(x)")}}</dt> + <dd>Returns the integral part of the number x, removing any fractional digits.</dd> +</dl> + +<h2 id="擴充_Math_物件">擴充 <code>Math</code> 物件</h2> + +<p>As most of the built-in objects in JavaScript, the <code>Math</code> object can be extended with custom properties and methods. To extend the <code>Math</code> object, you do not use 'prototype'. Instead, you directly extend <code>Math</code>:</p> + +<pre>Math.propName = propValue; +Math.methodName = methodRef;</pre> + +<p>For instance, the following example adds a method to the <code>Math</code> object for calculating the <em>greatest common divisor</em> of a list of arguments.</p> + +<pre class="brush: js">/* Variadic function -- Returns the greatest common divisor of a list of arguments */ +Math.gcd = function() { + if (arguments.length == 2) { + if (arguments[1] == 0) + return arguments[0]; + else + return Math.gcd(arguments[1], arguments[0] % arguments[1]); + } else if (arguments.length > 2) { + var result = Math.gcd(arguments[0], arguments[1]); + for (var i = 2; i < arguments.length; i++) + result = Math.gcd(result, arguments[i]); + return result; + } +};</pre> + +<p>Try it:</p> + +<pre class="brush: js">console.log(Math.gcd(20, 30, 15, 70, 40)); // `5`</pre> + +<h2 id="規範">規範</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.1.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.8', 'Math')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-math-object', 'Math')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>New methods {{jsxref("Math.log10()", "log10()")}}, {{jsxref("Math.log2()", "log2()")}}, {{jsxref("Math.log1p()", "log1p()")}}, {{jsxref("Math.expm1()", "expm1()")}}, {{jsxref("Math.cosh()", "cosh()")}}, {{jsxref("Math.sinh()", "sinh()")}}, {{jsxref("Math.tanh()", "tanh()")}}, {{jsxref("Math.acosh()", "acosh()")}}, {{jsxref("Math.asinh()", "asinh()")}}, {{jsxref("Math.atanh()", "atanh()")}}, {{jsxref("Math.hypot()", "hypot()")}}, {{jsxref("Math.trunc()", "trunc()")}}, {{jsxref("Math.sign()", "sign()")}}, {{jsxref("Math.imul()", "imul()")}}, {{jsxref("Math.fround()", "fround()")}}, {{jsxref("Math.cbrt()", "cbrt()")}} and {{jsxref("Math.clz32()", "clz32()")}} added.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-math-object', 'Math')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Math")}}</p> + +<h2 id="參見">參見</h2> + +<ul> + <li>{{jsxref("Number")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/math/max/index.html b/files/zh-tw/web/javascript/reference/global_objects/math/max/index.html new file mode 100644 index 0000000000..1f53898090 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/math/max/index.html @@ -0,0 +1,117 @@ +--- +title: Math.max() +slug: Web/JavaScript/Reference/Global_Objects/Math/max +tags: + - JavaScript + - Math + - Method + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Math/max +--- +<div>{{JSRef}}</div> + +<p><strong><code>Math.max()</code></strong> 函式會回傳零或多個數字中的最大值。</p> + +<div>{{EmbedInteractiveExample("pages/js/math-max.html")}}</div> + + + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox"><code>Math.max([<var>value1</var>[, <var>value2</var>[, ...]]])</code></pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>value1, value2, ...</code></dt> + <dd>Numbers.</dd> +</dl> + +<h3 id="Return_value">Return value</h3> + +<p>The largest of the given numbers. If at least one of the arguments cannot be converted to a number, {{jsxref("NaN")}} is returned.</p> + +<h2 id="說明">說明</h2> + +<p>Because <code>max()</code> is a static method of <code>Math</code>, you always use it as <code>Math.max()</code>, rather than as a method of a <code>Math</code> object you created (<code>Math</code> is not a constructor).</p> + +<p>If no arguments are given, the result is -{{jsxref("Infinity")}}.</p> + +<p>If at least one of arguments cannot be converted to a number, the result is {{jsxref("NaN")}}.</p> + +<h2 id="範例">範例</h2> + +<h3 id="Using_Math.max()">Using <code>Math.max()</code></h3> + +<pre class="brush: js">Math.max(10, 20); // 20 +Math.max(-10, -20); // -10 +Math.max(-10, 20); // 20 +</pre> + +<h4 id="Getting_the_maximum_element_of_an_array">Getting the maximum element of an array</h4> + +<p>{{jsxref("Array.prototype.reduce", "Array.reduce()")}} can be used to find the maximum element in a numeric array, by comparing each value:</p> + +<pre class="brush: js">var arr = [1,2,3]; +var max = arr.reduce(function(a, b) { + return Math.max(a, b); +}); +</pre> + +<p>The following function uses {{jsxref("Function.prototype.apply()")}} to get the maximum of an array. <code>getMaxOfArray([1, 2, 3])</code> is equivalent to <code>Math.max(1, 2, 3)</code>, but you can use <code>getMaxOfArray()</code> on programmatically constructed arrays. This should only be used for arrays with relatively few elements.</p> + +<pre class="brush: js">function getMaxOfArray(numArray) { + return Math.max.apply(null, numArray); +}</pre> + +<p>The new <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator">spread operator</a> is a shorter way of writing the <code>apply</code> solution to get the maximum of an array:</p> + +<pre class="brush: js">var arr = [1, 2, 3]; +var max = Math.max(...arr); +</pre> + +<p>However, both spread (<code>...</code>) and <code>apply</code> will either fail or return the wrong result if the array has too many elements, because they try to pass the array elements as function parameters. See <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply#Using_apply_and_built-in_functions">Using <code>apply</code> and built-in functions</a> for more details. The <code>reduce</code> solution does not have this problem.</p> + +<h2 id="規範">規範</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.8.2.11', 'Math.max')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-math.max', 'Math.max')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-math.max', 'Math.max')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Math.max")}}</p> + +<h2 id="參見">參見</h2> + +<ul> + <li>{{jsxref("Math.min()")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/math/pow/index.html b/files/zh-tw/web/javascript/reference/global_objects/math/pow/index.html new file mode 100644 index 0000000000..00ccb041ae --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/math/pow/index.html @@ -0,0 +1,107 @@ +--- +title: Math.pow() +slug: Web/JavaScript/Reference/Global_Objects/Math/pow +tags: + - 次方 +translation_of: Web/JavaScript/Reference/Global_Objects/Math/pow +--- +<div>{{JSRef}}</div> + +<p><strong><code>Math.pow()</code></strong> 函式回傳 <code>base</code> 的 <code>exponent</code> 次方(幂)值,也就是 <code>base<sup>exponent</sup></code>。</p> + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox notranslate"><code>Math.pow(<var>base</var>, <var>exponent</var>)</code></pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>base</code></dt> + <dd>基數。</dd> + <dt><code>exponent</code></dt> + <dd>要乘上 <code>base</code> 幾次的指數。</dd> +</dl> + +<h3 id="回傳值">回傳值</h3> + +<p>A number representing the given base taken to the power of the given exponent.</p> + +<h2 id="敘述">敘述</h2> + +<p>The <strong><code>Math.pow()</code></strong> function returns the <code>base</code> to the <code>exponent</code> power, that is, <code>base<sup>exponent</sup></code>, the base and the exponent are in decimal numeral system.</p> + +<p>由於 <code>pow()</code> 是 <code>Math</code> 的靜態方法,you always use it as <code>Math.pow()</code>, rather than as a method of a <code>Math</code> object you created(<code>Math</code> 並沒有建構子)。</p> + +<h2 id="示例">示例</h2> + +<h3 id="使用_Math.pow">使用 <code>Math.pow()</code></h3> + +<pre class="brush: js notranslate">// simple +Math.pow(7, 2); // 49 +Math.pow(7, 3); // 343 +Math.pow(2, 10); // 1024 +// fractional exponents +Math.pow(4, 0.5); // 2 (4 的平方根) +Math.pow(8, 1/3); // 2 (8 的立方根) +Math.pow(2, 0.5); // 1.4142135623730951 (2 的平方根) +Math.pow(2, 1/3); // 1.2599210498948732 (2 的立方根) +// signed exponents +Math.pow(7, -2); // 0.02040816326530612 (1/49) +Math.pow(8, -1/3); // 0.5 +// signed bases +Math.pow(-7, 2); // 49 (負負得正,2次方都是正數) +Math.pow(-7, 3); // -343 (3次方有可能為負數) +Math.pow(-7, 0.5); // NaN (負數沒辦法得出一個實數平方根) +// due to "even" and "odd" roots laying close to each other, +// and limits in the floating number precision, +// negative bases with fractional exponents always return NaN +Math.pow(-7, 1/3); // NaN +</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('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.8.2.13', 'Math.pow')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-math.pow', 'Math.pow')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-math.pow', 'Math.pow')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Math.pow")}}</p> + +<h2 id="參見">參見</h2> + +<ul> + <li>{{jsxref("Math.cbrt()")}}</li> + <li>{{jsxref("Math.exp()")}}</li> + <li>{{jsxref("Math.log()")}}</li> + <li>{{jsxref("Math.sqrt()")}}</li> + <li><a href="https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Exponentiation" title="Arithmetic operators take numerical values (either literals or variables) as their operands and return a single numerical value. The standard arithmetic operators are addition (+), subtraction (-), multiplication (*), and division (/).">Exponentiation operator</a> {{experimental_inline}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/math/random/index.html b/files/zh-tw/web/javascript/reference/global_objects/math/random/index.html new file mode 100644 index 0000000000..4f7b65f844 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/math/random/index.html @@ -0,0 +1,95 @@ +--- +title: Math.random() +slug: Web/JavaScript/Reference/Global_Objects/Math/random +tags: + - 浮點數 + - 隨機 +translation_of: Web/JavaScript/Reference/Global_Objects/Math/random +--- +<div>{{JSRef}}</div> + +<p>函數 <strong><code>Math.random()</code></strong> 會回傳一個偽隨機小數 (pseudo-random) 介於0到1之間(包含 0,不包含1) ,大致符合數學與統計上的均勻分佈 (uniform distribution) ,您可以選定想要的數字區間,它會透過演算法被產生並且不允許使用者自行跳選或重設成特定數字。{{EmbedInteractiveExample("pages/js/math-random.html")}}</p> + +<div class="note"> +<p><code>Math.random()</code> 所產生的偽隨機小數不符合加密學安全性要求。<em>請勿使用於任何加密、資安相關領域。</em></p> + +<p><em>如有加密需求建議參考Web Crypto API</em><a href="/en-US/docs/Web/API/RandomSource/getRandomValues" title="The documentation about this has not yet been written; please consider contributing!"><code>window.crypto.getRandomValues()</code></a></p> +</div> + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox notranslate">Math.random()</pre> + +<h3 id="回傳值_Return_value">回傳值 Return value</h3> + +<p>回傳一個偽隨機小數 (pseudo-random),小數也稱浮點數; 介於0到1之間(包含 0,不包含1) 。</p> + +<h2 id="範例">範例</h2> + +<p>請留意JavaScript中的數字與許多語言一樣使用 IEEE 754 floating point numbers with round-to-nearest-even behavior, the ranges claimed for the functions below (excluding the one for <code>Math.random()</code> itself) aren't exact. If extremely large bounds are chosen (2<sup>53</sup> or higher), it's possible in <em>extremely</em> rare cases to calculate the usually-excluded upper bound.</p> + +<h3 id="Getting_a_random_number_between_0_inclusive_and_1_exclusive">Getting a random number between 0 (inclusive) and 1 (exclusive)</h3> + +<pre class="brush: js notranslate">function getRandom() { + return Math.random(); +} +</pre> + +<h3 id="Getting_a_random_number_between_two_values">Getting a random number between two values</h3> + +<p>This example returns a random number between the specified values. The returned value is no lower than (and may possibly equal) <code>min</code>, and is less than (and not equal) <code>max</code>.</p> + +<pre class="brush: js notranslate">function getRandomArbitrary(min, max) { + return Math.random() * (max - min) + min; +} +</pre> + +<h3 id="Getting_a_random_integer_between_two_values">Getting a random integer between two values</h3> + +<p>This example returns a random <em>integer</em> between the specified values. The value is no lower than <code>min</code> (or the next integer greater than <code>min</code> if <code>min</code> isn't an integer), and is less than (but not equal to) <code>max</code>.</p> + +<pre class="brush: js notranslate">function getRandomInt(min, max) { + min = Math.ceil(min); + max = Math.floor(max); + return Math.floor(Math.random() * (max - min) + min); //The maximum is exclusive and the minimum is inclusive +} +</pre> + +<div class="note"> +<p>It might be tempting to use <code>Math.round()</code> to accomplish that, but doing so would cause your random numbers to follow a non-uniform distribution, which may not be acceptable for your needs.</p> +</div> + +<h3 id="Getting_a_random_integer_between_two_values_inclusive">Getting a random integer between two values, inclusive</h3> + +<p>While the <code>getRandomInt()</code> function above is inclusive at the minimum, it's exclusive at the maximum. What if you need the results to be inclusive at both the minimum and the maximum? The <code>getRandomIntInclusive()</code> function below accomplishes that.</p> + +<pre class="brush: js notranslate">function getRandomIntInclusive(min, max) { + min = Math.ceil(min); + max = Math.floor(max); + return Math.floor(Math.random() * (max - min + 1) + min); //The maximum is inclusive and the minimum is inclusive +}</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-math.random', 'Math.random')}}</td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Math.random")}}</p> + +<h2 class="countTop" id="其他參考資料">其他參考資料</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/RandomSource/getRandomValues" title="The documentation about this has not yet been written; please consider contributing!"><code>window.crypto.getRandomValues()</code></a></li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/math/round/index.html b/files/zh-tw/web/javascript/reference/global_objects/math/round/index.html new file mode 100644 index 0000000000..5e6a0ea694 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/math/round/index.html @@ -0,0 +1,212 @@ +--- +title: Math.round() +slug: Web/JavaScript/Reference/Global_Objects/Math/round +tags: + - JavaScript + - Math + - Method + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Math/round +--- +<div>{{JSRef}}</div> + +<p><strong><code>Math.round()</code></strong> 函數回傳四捨五入後的近似值.</p> + +<h2 id="表達式">表達式</h2> + +<pre class="syntaxbox"><code>Math.round(<var>x</var>)</code></pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>x</code></dt> + <dd>數字.</dd> +</dl> + +<h2 id="描述">描述</h2> + +<p>如果小數位的部分值大於 0.5, 這個值將會進位. 如果小數位的部分值小於 0.5, 這個值將不會進位.</p> + +<p>由於 <code>round()</code> 是靜態的方法, 所以總是得這樣使用 <code>Math.round()</code>, 而非作為 <code>Math</code> 物件的一個方法 (<code>Math</code>並沒有建構子).</p> + +<h2 id="範例">範例</h2> + +<h3 id="使用_Math.round()">使用 <code>Math.round()</code></h3> + +<pre class="brush: js">// Returns the value 20 +x = Math.round(20.49); + +// Returns the value 21 +x = Math.round(20.5); + +// Returns the value -20 +x = Math.round(-20.5); + +// Returns the value -21 +x = Math.round(-20.51); + +// Returns the value 1 (!) +// Note the rounding error because of inaccurate floating point arithmetics +// Compare this with Math.round10(1.005, -2) from the example below +x = Math.round(1.005*100)/100; +</pre> + +<h3 id="十進位近似值">十進位近似值</h3> + +<pre class="brush: js">// 閉包含數 +(function() { + /** + * Decimal adjustment of a number. + * + * @param {String} type The type of adjustment. + * @param {Number} value The number. + * @param {Integer} exp The exponent (the 10 logarithm of the adjustment base). + * @returns {Number} The adjusted value. + */ + function decimalAdjust(type, value, exp) { + // If the exp is undefined or zero... + if (typeof exp === 'undefined' || +exp === 0) { + return Math[type](value); + } + value = +value; + exp = +exp; + // If the value is not a number or the exp is not an integer... + if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) { + return NaN; + } + // Shift + value = value.toString().split('e'); + value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp))); + // Shift back + value = value.toString().split('e'); + return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp)); + } + + // Decimal round + if (!Math.round10) { + Math.round10 = function(value, exp) { + return decimalAdjust('round', value, exp); + }; + } + // Decimal floor + if (!Math.floor10) { + Math.floor10 = function(value, exp) { + return decimalAdjust('floor', value, exp); + }; + } + // Decimal ceil + if (!Math.ceil10) { + Math.ceil10 = function(value, exp) { + return decimalAdjust('ceil', value, exp); + }; + } +})(); + +// Round +Math.round10(55.55, -1); // 55.6 +Math.round10(55.549, -1); // 55.5 +Math.round10(55, 1); // 60 +Math.round10(54.9, 1); // 50 +Math.round10(-55.55, -1); // -55.5 +Math.round10(-55.551, -1); // -55.6 +Math.round10(-55, 1); // -50 +Math.round10(-55.1, 1); // -60 +Math.round10(1.005, -2); // 1.01 -- compare this with Math.round(1.005*100)/100 above +// Floor +Math.floor10(55.59, -1); // 55.5 +Math.floor10(59, 1); // 50 +Math.floor10(-55.51, -1); // -55.6 +Math.floor10(-51, 1); // -60 +// Ceil +Math.ceil10(55.51, -1); // 55.6 +Math.ceil10(51, 1); // 60 +Math.ceil10(-55.59, -1); // -55.5 +Math.ceil10(-59, 1); // -50 +</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('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.8.2.15', 'Math.round')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-math.round', 'Math.round')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Basic support</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>Feature</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</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>{{jsxref("Math.abs()")}}</li> + <li>{{jsxref("Math.ceil()")}}</li> + <li>{{jsxref("Math.floor()")}}</li> + <li>{{jsxref("Math.sign()")}} {{experimental_inline}}</li> + <li>{{jsxref("Math.trunc()")}} {{experimental_inline}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/nan/index.html b/files/zh-tw/web/javascript/reference/global_objects/nan/index.html new file mode 100644 index 0000000000..ef027d387f --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/nan/index.html @@ -0,0 +1,85 @@ +--- +title: NaN +slug: Web/JavaScript/Reference/Global_Objects/NaN +translation_of: Web/JavaScript/Reference/Global_Objects/NaN +--- +<div>{{jsSidebar("Objects")}}</div> + +<p>全域屬性 <code><strong>NaN</strong></code> 表示「非數值」(Not-A-Number)的數值。</p> + +<p>{{js_property_attributes(0,0,0)}}</p> + +<div>{{EmbedInteractiveExample("pages/js/globalprops-nan.html")}}</div> + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox"><code>NaN</code></pre> + +<h2 id="描述">描述</h2> + +<p><code>NaN</code> 的屬性屬於<em>全域物件</em>。</p> + +<p>如同 {{jsxref("Number.NaN")}} 一般,<code>NaN</code> 的初始數值是「非數值」。在當今的瀏覽器中,<code>NaN</code> 屬性不可設定(non-configurable)也不可覆寫(non-writable)。雖然可能有例外,也請不要覆蓋它。</p> + +<p>寫程式很少會直接動用 <code>NaN</code>。通常是在 {{jsxref("Math")}} 函式計算失敗(<code>Math.sqrt(-1)</code>)或函式解析數字失敗(<code>parseInt("blabla")</code>)後才會回傳。</p> + +<h3 id="偵測是否為_NaN">偵測是否為 <code>NaN</code></h3> + +<p><code>NaN</code> 不等於(<code>==</code>、<code>!=</code>、<code>===</code>、<code>!==</code>)任何值,包括 NaN 本身。請使用 {{jsxref("Number.isNaN()")}} 或 {{jsxref("Global_Objects/isNaN", "isNaN()")}} 來確認某個數值是否為 NaN。Or perform a self-comparison: NaN, and only NaN, will compare unequal to itself.</p> + +<pre class="brush: js">NaN === NaN; // false +Number.NaN === NaN; // false +isNaN(NaN); // true +isNaN(Number.NaN); // true + +function valueIsNaN(v) { return v !== v; } +valueIsNaN(1); // false +valueIsNaN(NaN); // true +valueIsNaN(Number.NaN); // true +</pre> + +<p>但請注意 <code>isNaN()</code> 與 <code>Number.isNaN()</code> 之間是有區別的:前者會在目前數字是 <code>NaN</code> 的時候回傳 <code>true</code>,或在裡面包藏一個號碼後變成 <code>NaN</code>;而後者,只有在數值是 <code>NaN</code> 的時候才會回傳 <code>true</code>。</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('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>初始定義。JavaScript 1.3 導入</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.1.1.1', 'NaN')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-value-properties-of-the-global-object-nan', 'NaN')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-value-properties-of-the-global-object-nan', 'NaN')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<p>{{Compat("javascript.builtins.NaN")}}</p> + +<h2 id="參見">參見</h2> + +<ul> + <li>{{jsxref("Number.NaN")}}</li> + <li>{{jsxref("Number.isNaN()")}}</li> + <li>{{jsxref("isNaN", "isNaN()")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/null/index.html b/files/zh-tw/web/javascript/reference/global_objects/null/index.html new file mode 100644 index 0000000000..0af88facab --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/null/index.html @@ -0,0 +1,124 @@ +--- +title: 'null' +slug: Web/JavaScript/Reference/Global_Objects/null +translation_of: Web/JavaScript/Reference/Global_Objects/null +--- +<div>{{jsSidebar("Objects")}}</div> + +<p>The value <code>null</code> represents the intentional absence of any object value. It is one of JavaScript's {{Glossary("Primitive", "primitive values")}}.</p> + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox"><code>null </code></pre> + +<h2 id="描述">描述</h2> + +<p>The value <code>null</code> is written with a literal, <code>null</code> (it's not an identifer for a property of the global object like {{jsxref("Global_Objects/undefined","undefined")}} can be). In APIs, <code>null</code> is often retrieved in place where an object can be expected but no object is relevant. When checking for null or undefined beware of the <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators">differences between equality (==) and identity (===) operators</a> (type-conversion is performed with the former).</p> + +<pre class="brush: js">// foo does not exist. It is not defined and has never been initialized: +> foo +"ReferenceError: foo is not defined" + +// foo is known to exist now but it has no type or value: +> var foo = null; foo +"null" +</pre> + +<h3 id="Difference_between_null_and_undefined">Difference between <code>null</code> and <code>undefined</code></h3> + +<pre class="brush: js">typeof null // object (bug in ECMAScript, should be null) +typeof undefined // undefined +null === undefined // false +null == undefined // true +</pre> + +<h2 id="規範">規範</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-4.3.11', 'null value')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-null-value', 'null value')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-null-value', 'null value')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</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>Feature</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>Basic support</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>{{jsxref("undefined")}}</li> + <li>{{jsxref("NaN")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/number/index.html b/files/zh-tw/web/javascript/reference/global_objects/number/index.html new file mode 100644 index 0000000000..8a023d1603 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/number/index.html @@ -0,0 +1,219 @@ +--- +title: Number +slug: Web/JavaScript/Reference/Global_Objects/Number +tags: + - JavaScript + - NeedsTranslation + - Number + - Reference + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/Number +--- +<div>{{JSRef}}</div> + +<p><strong><code>Number</code></strong> JavaScript 物件是允許你操作數值的包覆物件. <code>Number</code> 物件是以 <code>Number()</code> 建構子來建立的。</p> + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox">new Number(value);</pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>value</code></dt> + <dd>用來建立物件的數值。</dd> +</dl> + +<h2 id="說明">說明</h2> + +<p><code>Number</code> 物件主要的用途:</p> + +<ul> + <li>如果參數沒辦法被轉換成數字,則它會回傳 {{jsxref("NaN")}} 。</li> + <li>在不是使用建構式的情境中(即不用 {{jsxref("Operators/new", "new")}} 運算子), <code>Number</code> 可以被用來轉換型別.</li> +</ul> + +<h2 id="屬性">屬性</h2> + +<dl> + <dt>{{jsxref("Number.EPSILON")}}</dt> + <dd>介於1和大於1的最小值之可表示的差。</dd> + <dt>{{jsxref("Number.MAX_SAFE_INTEGER")}}</dt> + <dd>JavaScript 中 IEEE-754 雙精度範圍間的最大整數 (<code>2<sup>53</sup> - 1</code>) 。</dd> + <dt>{{jsxref("Number.MAX_VALUE")}}</dt> + <dd>可表示的最大正整數。</dd> + <dt>{{jsxref("Number.MIN_SAFE_INTEGER")}}</dt> + <dd>JavaScript 中 IEEE-754 雙精度範圍間的最小整數 (<code>-(2<sup>53</sup> - 1)</code>) 。</dd> + <dt>{{jsxref("Number.MIN_VALUE")}}</dt> + <dd>可表示的最小值,即最靠近0的正整數?(<code><math><semantics><mrow><mn>5.00</mn><mo>×</mo><msup><mn>10</mn><mn>324</mn></msup></mrow><annotation encoding="TeX">5.00\times10^{324}</annotation></semantics></math></code>)。</dd> + <dt>{{jsxref("Number.NaN")}}</dt> + <dd>特別用來表示<strong>非數值</strong>的物件。</dd> + <dt>{{jsxref("Number.NEGATIVE_INFINITY")}}</dt> + <dd>特別用來表示<strong>負無窮</strong>的數值。</dd> + <dt>{{jsxref("Number.POSITIVE_INFINITY")}}</dt> + <dd>特別用來表示<strong>正無窮</strong>的數值。</dd> + <dt>{{jsxref("Number.prototype")}}</dt> + <dd>允許被添加到 <code>Number</code> 物件的屬性。</dd> +</dl> + +<h2 id="方法">方法</h2> + +<dl> + <dt>{{jsxref("Number.isNaN()")}}</dt> + <dd>判斷傳入的值是不是 NaN.</dd> + <dt>{{jsxref("Number.isFinite()")}}</dt> + <dd>判斷傳入的值是不是一個有限的數值。</dd> + <dt>{{jsxref("Number.isInteger()")}}</dt> + <dd>判斷傳入的值是不是一個整數。</dd> + <dt>{{jsxref("Number.isSafeInteger()")}}</dt> + <dd>判斷傳入的值是不是在 IEEE-754 雙精度範圍間 (即介於 <code>-(2<sup>53</sup> - 1)</code> 和 <code>2<sup>53</sup> - 1</code>之前)。</dd> + <dt><s class="obsoleteElement">{{jsxref("Number.toInteger()")}} {{obsolete_inline}}</s></dt> + <dd><s class="obsoleteElement">被用來評估傳入的值且將其轉換成整數 (或 {{jsxref("Global_Objects/Infinity", "Infinity")}}) 但已被移除。</s></dd> + <dt>{{jsxref("Number.parseFloat()")}}</dt> + <dd>這個方法和全域物件的 {{jsxref("parseFloat", "parseFloat()")}} 相同。</dd> + <dt>{{jsxref("Number.parseInt()")}}</dt> + <dd>這個方法和全域物件的 {{jsxref("parseInt", "parseInt()")}} 相同。</dd> +</dl> + +<h2 id="Number_實體"><code>Number</code> 實體</h2> + +<p>所有 <code>Number</code> 實體都會繼承其建構式的 {{jsxref("Number.prototype")}}。<code>Number</code> 的原型物件可以被修改並作用在所有 <code>Number</code> 實體。</p> + +<h3 id="方法_2">方法</h3> + +<div>{{page('/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Number/prototype', '方法')}}</div> + +<h2 id="範例">範例</h2> + +<h3 id="使用_Number_物件去指派值給數值變數">使用 <code>Number</code> 物件去指派值給數值變數</h3> + +<p>下列的範例使用 <code>Number</code> 物件的屬性去指派值給數個數值變數:</p> + +<pre class="brush: js">var biggestNum = Number.MAX_VALUE; +var smallestNum = Number.MIN_VALUE; +var infiniteNum = Number.POSITIVE_INFINITY; +var negInfiniteNum = Number.NEGATIVE_INFINITY; +var notANum = Number.NaN; +</pre> + +<h3 id="Number_的整數範圍"><code>Number</code> 的整數範圍</h3> + +<p>下面的範例展示了最小和最大的整數,其可以被表示成 <code>Number</code> 物件(細節請參考 ECMAScript standard, chapter <em>8.5 The Number Type</em>):</p> + +<pre class="brush: js">var biggestInt = 9007199254740992; +var smallestInt = -9007199254740992; +</pre> + +<p>當在解析已經被序列化的 JSON 的資料時,填入這個範圍之外的整數並且 JSON 剖析器強制將其轉成 <code>Number</code> 型別造成損壞是可預期的。將範圍之外的正數換成以 {{jsxref("String")}} 表示反倒是一個可行的替代方案。</p> + +<h3 id="使用_Number_轉換_Date_物件為_Unix_時間戳記">使用 <code>Number</code> 轉換 <code>Date</code> 物件為 Unix 時間戳記</h3> + +<p>下面的範例將 <code>Number</code> 視為函式,並且使用它將 {{jsxref("Date")}} 轉換成時間戳記:</p> + +<pre class="brush: js">var d = new Date('December 17, 1995 03:24:00'); +console.log(Number(d)); // 819199440000 + +</pre> + +<h3 id="轉換數值字串成數值">轉換數值字串成數值</h3> + +<pre class="brush: js">Number("123") // 123 +Number("12.3") // 12.3 +Number("") // 0 +Number("0x11") // 17 +Number("0b11") // 3 +Number("0o11") // 9 +Number("foo") // NaN +Number("100a") // NaN +</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('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.1.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.7', 'Number')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-number-objects', 'Number')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>New methods and properties added: {{jsxref("Number.EPSILON", "EPSILON")}}, {{jsxref("Number.isFinite", "isFinite")}}, {{jsxref("Number.isInteger", "isInteger")}}, {{jsxref("Number.isNaN", "isNaN")}}, {{jsxref("Number.parseFloat", "parseFloat")}}, {{jsxref("Number.parseInt", "parseInt")}}</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-number-objects', 'Number')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容">瀏覽器相容</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</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>Feature</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>Basic support</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>{{jsxref("NaN")}}</li> + <li>The {{jsxref("Math")}} global object</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/number/isfinite/index.html b/files/zh-tw/web/javascript/reference/global_objects/number/isfinite/index.html new file mode 100644 index 0000000000..a15d29c7c0 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/number/isfinite/index.html @@ -0,0 +1,93 @@ +--- +title: Number.isFinite() +slug: Web/JavaScript/Reference/Global_Objects/Number/isFinite +tags: + - JavaScript + - Method + - Number + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Number/isFinite +--- +<div>{{JSRef}}</div> + +<p><strong><code>Number.isFinite()</code></strong> 方法會判斷傳入的值是否為有限數(finite number)。</p> + +<div>{{EmbedInteractiveExample("pages/js/number-isfinite.html")}}</div> + + + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox">Number.isFinite(v<var>alue</var>)</pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>value</code></dt> + <dd>The value to be tested for finiteness.</dd> +</dl> + +<h3 id="回傳值">回傳值</h3> + +<p>A {{jsxref("Boolean")}} indicating whether or not the given value is a finite number.</p> + +<h2 id="說明">說明</h2> + +<p>In comparison to the global {{jsxref("isFinite", "isFinite()")}} function, this method doesn't forcibly convert the parameter to a number. This means only values of the type number, that are also finite, return <code>true</code>.</p> + +<h2 id="範例">範例</h2> + +<pre class="brush: js">Number.isFinite(Infinity); // false +Number.isFinite(NaN); // false +Number.isFinite(-Infinity); // false + +Number.isFinite(0); // true +Number.isFinite(2e64); // true + +Number.isFinite('0'); // false, would've been true with + // global isFinite('0') +Number.isFinite(null); // false, would've been true with + // global isFinite(null) +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<pre class="brush: js">Number.isFinite = Number.isFinite || function(value) { + return typeof value === 'number' && isFinite(value); +} +</pre> + +<h2 id="規範">規範</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-number.isfinite', 'Number.isInteger')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-number.isfinite', 'Number.isInteger')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Number.isFinite")}}</p> + +<h2 id="參見">參見</h2> + +<ul> + <li>The {{jsxref("Number")}} object it belongs to.</li> + <li>The global function {{jsxref("isFinite")}}.</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/number/isnan/index.html b/files/zh-tw/web/javascript/reference/global_objects/number/isnan/index.html new file mode 100644 index 0000000000..9209e40779 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/number/isnan/index.html @@ -0,0 +1,99 @@ +--- +title: Number.isNaN() +slug: Web/JavaScript/Reference/Global_Objects/Number/isNaN +translation_of: Web/JavaScript/Reference/Global_Objects/Number/isNaN +--- +<div>{{JSRef}}</div> + +<p>The <strong><code>Number.isNaN()</code></strong> method determines whether the passed value is {{jsxref("NaN")}} and its type is {{jsxref("Number")}}. It is a more robust version of the original, global {{jsxref("isNaN", "isNaN()")}}.</p> + +<div>{{EmbedInteractiveExample("pages/js/number-isnan.html", "taller")}}</div> + + + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><code>Number.isNaN(<var>value</var>)</code></pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>value</code></dt> + <dd>The value to be tested for {{jsxref("NaN")}}.</dd> +</dl> + +<h3 id="Return_value">Return value</h3> + +<p><strong>true</strong> if the given value is {{jsxref("NaN")}} and its type is {{jsxref("Number")}}; otherwise, <strong>false</strong>.</p> + +<h2 id="Description">Description</h2> + +<p>Due to both equality operators, {{jsxref("Operators/Comparison_Operators", "==", "#Equality")}} and {{jsxref("Operators/Comparison_Operators", "===", "#Identity")}}, evaluating to <code>false</code> when checking if {{jsxref("NaN")}} <em>is</em> {{jsxref("NaN")}}, the function <code>Number.isNaN()</code> has become necessary. This situation is unlike all other possible value comparisons in JavaScript.</p> + +<p>In comparison to the global {{jsxref("isNaN", "isNaN()")}} function, <code>Number.isNaN()</code> doesn't suffer the problem of forcefully converting the parameter to a number. This means it is now safe to pass values that would normally convert to {{jsxref("NaN")}}, but aren't actually the same value as {{jsxref("NaN")}}. This also means that only values of the type number, that are also {{jsxref("NaN")}}, return <code>true</code>.</p> + +<h2 id="Examples">Examples</h2> + +<pre class="brush: js">Number.isNaN(NaN); // true +Number.isNaN(Number.NaN); // true +Number.isNaN(0 / 0); // true + +// e.g. these would have been true with global isNaN() +Number.isNaN('NaN'); // false +Number.isNaN(undefined); // false +Number.isNaN({}); // false +Number.isNaN('blabla'); // false + +// These all return false +Number.isNaN(true); +Number.isNaN(null); +Number.isNaN(37); +Number.isNaN('37'); +Number.isNaN('37.37'); +Number.isNaN(''); +Number.isNaN(' '); +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p>The following works because NaN is the only value in javascript which is not equal to itself.</p> + +<pre class="brush: js">Number.isNaN = Number.isNaN || function(value) { + return value !== value; +} +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-number.isnan', 'Number.isnan')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-number.isnan', 'Number.isnan')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Number.isNaN")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Number")}}</li> + <li>{{jsxref("isNaN", "isNaN()")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/number/prototype/index.html b/files/zh-tw/web/javascript/reference/global_objects/number/prototype/index.html new file mode 100644 index 0000000000..2a41977a2d --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/number/prototype/index.html @@ -0,0 +1,84 @@ +--- +title: Number.prototype +slug: Web/JavaScript/Reference/Global_Objects/Number/prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Number +--- +<div>{{JSRef}}</div> + +<p><strong><code>Number.prototype</code></strong> 屬性用來表示 {{jsxref("Number")}} 建構式的原型。</p> + +<div>{{js_property_attributes(0, 0, 0)}}</div> + +<h2 id="說明">說明</h2> + +<p>所有 {{jsxref("Number")}} 實體都繼承自 <code>Number.prototype</code> 。{{jsxref("Number")}} 建構式的原型物件可以被修改並作用在所有 {{jsxref("Number")}} 實體。</p> + +<h2 id="屬性">屬性</h2> + +<dl> + <dt><code>Number.prototype.constructor</code></dt> + <dd>回傳建立這個物件實體的建構式。預設為 {{jsxref("Number")}} 物件。</dd> +</dl> + +<h2 id="方法">方法</h2> + +<dl> + <dt>{{jsxref("Number.prototype.toExponential()")}}</dt> + <dd>回傳以「科學記數法」表示的數值字串。</dd> + <dt>{{jsxref("Number.prototype.toFixed()")}}</dt> + <dd>回傳以定點表示的數值字串。</dd> + <dt>{{jsxref("Number.prototype.toLocaleString()")}}</dt> + <dd>回傳以當地語言為主的數值字串。這覆寫 {{jsxref("Object.prototype.toLocaleString()")}} 的方法。</dd> + <dt>{{jsxref("Number.prototype.toPrecision()")}}</dt> + <dd>回傳以定點或科學記數表示的數值字串。</dd> + <dt>{{jsxref("Number.prototype.toSource()")}} {{non-standard_inline}}</dt> + <dd>Returns an object literal representing the specified {{jsxref("Number")}} object; you can use this value to create a new object. Overrides the {{jsxref("Object.prototype.toSource()")}} method.</dd> + <dt>{{jsxref("Number.prototype.toString()")}}</dt> + <dd>回傳以特定基數表示的數值字串。這覆寫 {{jsxref("Object.prototype.toString()")}} 的方法 。</dd> + <dt>{{jsxref("Number.prototype.valueOf()")}}</dt> + <dd>回傳這個物件的原始型別,即原始數值。這覆寫 {{jsxref("Object.prototype.valueOf()")}} 。</dd> +</dl> + +<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('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.1.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.7.4', 'Number')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-properties-of-the-number-prototype-object', 'Number')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-properties-of-the-number-prototype-object', 'Number')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Number.prototype")}}</p> + +<h2 id="參見">參見</h2> + +<ul> + <li>{{jsxref("Number")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/number/toexponential/index.html b/files/zh-tw/web/javascript/reference/global_objects/number/toexponential/index.html new file mode 100644 index 0000000000..622314ecfb --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/number/toexponential/index.html @@ -0,0 +1,164 @@ +--- +title: Number.prototype.toExponential() +slug: Web/JavaScript/Reference/Global_Objects/Number/toExponential +tags: + - 數字 + - 科學技數法 +translation_of: Web/JavaScript/Reference/Global_Objects/Number/toExponential +--- +<div>{{JSRef}}</div> + +<p><strong><code>toExponential()</code></strong> method 用來將數字轉成「科學記數法」格式。</p> + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox"><code><var>numObj</var>.toExponential([<var>fractionDigits</var>])</code></pre> + +<h3 id="參數">參數</h3> + +<table class="standard-table"> + <thead> + <tr> + <th>參數</th> + <th>可選</th> + <th>默認值</th> + <th>類型</th> + <th>說明</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>fractionDigits</code></td> + <td>●</td> + <td><font face="Consolas, Liberation Mono, Courier, monospace">默認盡可能將數字完整顯示</font></td> + <td><code>{{jsxref("Number")}}(正整數)</code></td> + <td>小數點後的位數。需為 0 至 20 之間。</td> + </tr> + </tbody> +</table> + +<h3 id="回傳直">回傳直</h3> + +<p>一 string,將數字以「科學計數法」格式表示出來</p> + +<h3 id="Exceptions">Exceptions</h3> + +<dl> + <dt>{{jsxref("RangeError")}}</dt> + <dd><code>若 fractionDigits</code> 超出範圍(可接受的範圍是 0 ~ 20 之間的正整數)觸發 {{jsxref("RangeError")}}。</dd> + <dt>{{jsxref("TypeError")}}</dt> + <dd>若參數 <code>fractionDigits</code> 不是 {{jsxref("Number")}},則觸發{{jsxref("TypeError")}}。</dd> +</dl> + +<h2 id="Description">Description</h2> + +<p>If the <code>fractionDigits</code> argument is omitted, the number of digits after the decimal point defaults to the number of digits necessary to represent the value uniquely.</p> + +<p>If you use the <code>toExponential()</code> method for a numeric literal and the numeric literal has no exponent and no decimal point, leave whitespace(s) before the dot that precedes the method call to prevent the dot from being interpreted as a decimal point.</p> + +<p>If a number has more digits than requested by the <code>fractionDigits</code> parameter, the number is rounded to the nearest number represented by <code>fractionDigits</code> digits. See the discussion of rounding in the description of the {{jsxref("Number.prototype.toFixed", "toFixed()")}} method, which also applies to <code>toExponential()</code>.</p> + +<h2 id="範例">範例</h2> + +<h3 id="Using_toExponential">Using <code>toExponential</code></h3> + +<pre class="brush: js">var numObj = 77.1234; + +console.log(numObj.toExponential()); // logs 7.71234e+1 +console.log(numObj.toExponential(4)); // logs 7.7123e+1 +console.log(numObj.toExponential(2)); // logs 7.71e+1 +console.log(77.1234.toExponential()); // logs 7.71234e+1 +console.log(77 .toExponential()); // logs 7.7e+1 +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Initial definition. Implemented in JavaScript 1.5.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.7.4.6', 'Number.prototype.toExponential')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-number.prototype.toexponential', 'Number.prototype.toExponential')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-number.prototype.toexponential', 'Number.prototype.toExponential')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器支援度">瀏覽器支援度</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</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>Feature</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>Basic support</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>{{jsxref("Number.prototype.toFixed()")}}</li> + <li>{{jsxref("Number.prototype.toPrecision()")}}</li> + <li>{{jsxref("Number.prototype.toString()")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/number/tofixed/index.html b/files/zh-tw/web/javascript/reference/global_objects/number/tofixed/index.html new file mode 100644 index 0000000000..7a5afb608f --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/number/tofixed/index.html @@ -0,0 +1,108 @@ +--- +title: Number.prototype.toFixed() +slug: Web/JavaScript/Reference/Global_Objects/Number/toFixed +tags: + - JavaScript + - Method + - Number + - Prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Number/toFixed +--- +<div>{{JSRef}}</div> + +<p><strong><code>toFixed()</code></strong> 方法會使用定點小數表示法(fixed-point notation)來格式化數字。</p> + +<div>{{EmbedInteractiveExample("pages/js/number-tofixed.html")}}</div> + + + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox notranslate"><code><var>numObj</var>.toFixed([<var>digits</var>])</code></pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>digits 小數位</code></dt> + <dd>選擇性輸入。顯示數值至多少個小數點,範圍由0到20之間,執行時或可支援非常大範圍的數值。如果無輸入會默認做0。</dd> +</dl> + +<h3 id="回傳值">回傳值</h3> + +<p>一個代表以定點小數表示法(fixed-point notation)格式化數字後的字串。</p> + +<h3 id="例外">例外</h3> + +<dl> + <dt>{{jsxref("RangeError")}}</dt> + <dd>If <code>digits</code> is too small or too large. Values between 0 and 100, inclusive, will not cause a {{jsxref("RangeError")}}. Implementations are allowed to support larger and smaller values as chosen.</dd> + <dt>{{jsxref("TypeError")}}</dt> + <dd>If this method is invoked on an object that is not a {{jsxref( "Number")}}.</dd> +</dl> + +<h2 id="說明">說明</h2> + +<p><strong><code>toFixed()</code></strong> returns a string representation of <code>numObj</code> that does not use exponential notation and has exactly <code>digits</code> digits after the decimal place. The number is rounded if necessary, and the fractional part is padded with zeros if necessary so that it has the specified length. If <code>numObj</code> is greater than <code>1e+21</code>, this method simply calls {{jsxref("Number.prototype.toString()")}} and returns a string in exponential notation.</p> + +<h2 id="範例">範例</h2> + +<h3 id="Using_toFixed">Using <code>toFixed</code></h3> + +<pre class="brush: js notranslate">var numObj = 12345.6789; + +numObj.toFixed(); // Returns '12346': note rounding, no fractional part +numObj.toFixed(1); // Returns '12345.7': note rounding +numObj.toFixed(6); // Returns '12345.678900': note added zeros +(1.23e+20).toFixed(2); // Returns '123000000000000000000.00' +(1.23e-10).toFixed(2); // Returns '0.00' +2.34.toFixed(1); // Returns '2.3' +2.35.toFixed(1); // Returns '2.4'. Note that it rounds up in this case. +-2.34.toFixed(1); // Returns -2.3 (due to operator precedence, negative number literals don't return a string...) +(-2.34).toFixed(1); // Returns '-2.3' (...unless you use parentheses) +</pre> + +<h2 id="規範">規範</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Initial definition. Implemented in JavaScript 1.5.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.7.4.5', 'Number.prototype.toFixed')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-number.prototype.tofixed', 'Number.prototype.toFixed')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-number.prototype.tofixed', 'Number.prototype.toFixed')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Number.toFixed")}}</p> + +<h2 id="參見">參見</h2> + +<ul> + <li>{{jsxref("Number.prototype.toExponential()")}}</li> + <li>{{jsxref("Number.prototype.toPrecision()")}}</li> + <li>{{jsxref("Number.prototype.toString()")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/object/assign/index.html b/files/zh-tw/web/javascript/reference/global_objects/object/assign/index.html new file mode 100644 index 0000000000..f4dfca5af7 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/object/assign/index.html @@ -0,0 +1,249 @@ +--- +title: Object.assign() +slug: Web/JavaScript/Reference/Global_Objects/Object/assign +translation_of: Web/JavaScript/Reference/Global_Objects/Object/assign +--- +<div>{{JSRef}}</div> + +<div><strong><code>Object.assign()</code></strong>被用來複製一個或多個物件自身所有可數的屬性到另一個目標物件。回傳的值為該目標物件。</div> + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox notranslate">Object.assign(<var>target</var>, ...<var>sources</var>)</pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>target</code></dt> + <dd>目標物件</dd> + <dt><code>sources</code></dt> + <dd>來源物件</dd> +</dl> + +<h3 id="回傳值">回傳值</h3> + +<p> 合併目標物件及(多個)來源物件所得到的最終物件。</p> + +<h2 id="說明">說明</h2> + +<p>如果在目標物件裡的屬性名稱(key)和來源物件的屬性名稱相同,將會被覆寫。若來源物件之間又有相同的屬性名稱,則後者會將前者覆寫。</p> + +<p><code>Object.assign()</code>只會從來源物件將自身可列舉的屬性複製到目標物件。此函式方法(method) 使用來源物件的<code>[[Get]]</code>事件和目標物件的<code>[[Set]]</code>事件,使它將會執行getters和setters。因此,這邊的指派(<em>assigns</em>)屬性不只是複製或定義新屬性。若在合併包含getters的來源物件時,這個事件可能就不適合用來合併屬性。至於複製屬性的定義(包含其可列舉性)到各屬性,反倒是會用到 {{jsxref("Object.getOwnPropertyDescriptor()")}} 和 {{jsxref("Object.defineProperty()")}} 。</p> + +<p>{{jsxref("String")}} 和 {{jsxref("Symbol")}} 類型的屬性都會被複製。</p> + +<p>若發生錯誤,例如: 當一個屬性不可被寫入時,將會引發 {{jsxref("TypeError")}} 的錯誤,且目標物件剩餘的屬性將不會改變。</p> + +<p>注意: <code>Object.assign()</code> 不會在來源物件屬性的值為{{jsxref("null")}} 或 {{jsxref("undefined")}} 的時候拋出錯誤。</p> + +<h2 id="範例">範例</h2> + +<h3 id="複製物件">複製物件</h3> + +<pre class="brush: js notranslate">var obj = { a: 1 }; +var copy = Object.assign({}, obj); +console.log(copy); // { a: 1 } +</pre> + +<h3 id="Deep_Clone" name="Deep_Clone">警告:非深層複製</h3> + +<p>深層複製(deep clone)需要使用其他的替代方案,因為 <code>Object.assign()</code> 僅複製屬性值。若來源物件的值參照到一個子物件,它只會複製該子物件的參照。</p> + +<pre class="brush: js notranslate">function test() { + let a = { b: {c:4} , d: { e: {f:1}} } + let g = Object.assign({},a) // 淺層 + let h = JSON.parse(JSON.stringify(a)); // 深層 + console.log(g.d) // { e: { f: 1 } } + g.d.e = 32 + console.log('g.d.e set to 32.') // g.d.e set to 32. + console.log(g) // { b: { c: 4 }, d: { e: 32 } } + console.log(a) // { b: { c: 4 }, d: { e: 32 } } + console.log(h) // { b: { c: 4 }, d: { e: { f: 1 } } } + h.d.e = 54 + console.log('h.d.e set to 54.') // h.d.e set to 54. + console.log(g) // { b: { c: 4 }, d: { e: 32 } } + console.log(a) // { b: { c: 4 }, d: { e: 32 } } + console.log(h) // { b: { c: 4 }, d: { e: 54 } } +} +test(); +</pre> + +<h3 id="合併物件">合併物件</h3> + +<pre class="brush: js notranslate">var o1 = { a: 1 }; +var o2 = { b: 2 }; +var o3 = { c: 3 }; + +var obj = Object.assign(o1, o2, o3); +console.log(obj); // { a: 1, b: 2, c: 3 } +console.log(o1); // { a: 1, b: 2, c: 3 }, 目標物件本身也被改變。</pre> + +<h3 id="有相同屬性時合併物件">有相同屬性時合併物件</h3> + +<pre class="brush: js notranslate">var o1 = { a: 1, b: 1, c: 1 }; +var o2 = { b: 2, c: 2 }; +var o3 = { c: 3 }; + +var obj = Object.assign({}, o1, o2, o3); +console.log(obj); // { a: 1, b: 2, c: 3 },屬性c為o3.c的值,最後一個出現的屬性c。</pre> + +<p>所有的屬性會被後方相同屬性名稱的值覆寫。</p> + +<h3 id="複製_Symbol_型別的屬性">複製 Symbol 型別的屬性</h3> + +<pre class="brush: js notranslate">var o1 = { a: 1 }; +var o2 = { [Symbol('foo')]: 2 }; + +var obj = Object.assign({}, o1, o2); +console.log(obj); // { a : 1, [Symbol("foo")]: 2 } (cf. bug 1207182 on Firefox) +Object.getOwnPropertySymbols(obj); // [Symbol(foo)]非不在 +</pre> + +<h3 id="在屬性鏈中的不可列舉屬性不會被複製">在屬性鏈中的不可列舉屬性不會被複製</h3> + +<pre class="brush: js notranslate">var obj = Object.create({ foo: 1 }, { // foo 是 obj 的屬性鏈。 + bar: { + value: 2 // bar 是不可列舉的屬性,因為enumerable預設為false。 + }, + baz: { + value: 3, + enumerable: true // baz 是自身可列舉的屬性。 + } +}); + +var copy = Object.assign({}, obj); +console.log(copy); // { baz: 3 } +</pre> + +<h3 id="原始型別會被包成物件">原始型別會被包成物件</h3> + +<pre class="brush: js notranslate">var v1 = 'abc'; +var v2 = true; +var v3 = 10; +var v4 = Symbol('foo'); + +var obj = Object.assign({}, v1, null, v2, undefined, v3, v4); +// 原始型別會被打包,null和undefined則會被忽略。 +// 注意: 只有打包成物件的字串是可列舉的,即可被複製的。 +console.log(obj); // { "0": "a", "1": "b", "2": "c" } +</pre> + +<h3 id="任何異常將會中斷正進行的複製程序">任何異常將會中斷正進行的複製程序</h3> + +<pre class="brush: js notranslate">var target = Object.defineProperty({}, 'foo', { + value: 1, + writable: false +}); // target.foo 是 read-only (唯讀)屬性 + +Object.assign(target, { bar: 2 }, { foo2: 3, foo: 3, foo3: 3 }, { baz: 4 }); +// TypeError: "foo" 是 read-only +// 在指派值給 target.foo 時,異常(Exception)會被拋出。 + +console.log(target.bar); // 2, 第一個來源物件複製成功。 +console.log(target.foo2); // 3, 第二個來源物件的第一個屬性複製成功。 +console.log(target.foo); // 1, 異常在這裡拋出。 +console.log(target.foo3); // undefined, 複製程式已中斷,複製失敗。 +console.log(target.baz); // undefined, 第三個來源物件也不會被複製。 +</pre> + +<h3 id="複製的存取程序">複製的存取程序</h3> + +<pre class="brush: js notranslate">var obj = { + foo: 1, + get bar() { + return 2; + } +}; + +var copy = Object.assign({}, obj); +console.log(copy); +// { foo: 1, bar: 2 }, copy.bar的值,是obj.bar的getter回傳的值。 + +// 這個函式用來複製完整的描述內容。 +function completeAssign(target, ...sources) { + sources.forEach(source => { + let descriptors = Object.keys(source).reduce((descriptors, key) => { + descriptors[key] = Object.getOwnPropertyDescriptor(source, key); + return descriptors; + }, {}); + // Object.assign 預設會複製可列舉的Symbols。 + Object.getOwnPropertySymbols(source).forEach(sym => { + let descriptor = Object.getOwnPropertyDescriptor(source, sym); + if (descriptor.enumerable) { + descriptors[sym] = descriptor; + } + }); + Object.defineProperties(target, descriptors); + }); + return target; +} + +var copy = completeAssign({}, obj); +console.log(copy); +// { foo:1, get bar() { return 2 } } +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p>{{Glossary("Polyfill","polyfill")}} 不支援Symbol屬性,因為ES5沒有Symbol型別。</p> + +<pre class="brush: js notranslate">if (typeof Object.assign != 'function') { + Object.assign = function (target, varArgs) { // .length of function is 2 + 'use strict'; + if (target == null) { // TypeError if undefined or null + throw new TypeError('Cannot convert undefined or null to object'); + } + + var to = Object(target); + + for (var index = 1; index < arguments.length; index++) { + var nextSource = arguments[index]; + + if (nextSource != null) { // Skip over if undefined or null + for (var nextKey in nextSource) { + // Avoid bugs when hasOwnProperty is shadowed + if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) { + to[nextKey] = nextSource[nextKey]; + } + } + } + } + return to; + }; +} +</pre> + +<h2 id="規格">規格</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object.assign', 'Object.assign')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-object.assign', 'Object.assign')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<div>{{Compat("javascript.builtins.Object.assign")}}</div> + +<div id="compat-desktop"></div> + +<h2 id="參閱">參閱</h2> + +<ul> + <li>{{jsxref("Object.defineProperties()")}}</li> + <li><a href="/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties">Enumerability and ownership of properties</a></li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/object/create/index.html b/files/zh-tw/web/javascript/reference/global_objects/object/create/index.html new file mode 100644 index 0000000000..f158d36977 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/object/create/index.html @@ -0,0 +1,258 @@ +--- +title: Object.create() +slug: Web/JavaScript/Reference/Global_Objects/Object/create +translation_of: Web/JavaScript/Reference/Global_Objects/Object/create +--- +<div>{{JSRef}}</div> + +<p><code><strong>Object.create()</strong></code> 指定其原型物件與屬性,創建一個新物件。</p> + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox">Object.create(<var>proto</var>[, <var>propertiesObject</var>])</pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>proto</code></dt> + <dd>指定新物件的原型 (prototype) 物件。</dd> + <dt><code>propertiesObject</code></dt> + <dd>選用,為一物件。如有指定且非 {{jsxref("undefined")}},則此參數物件中可列舉出的屬性 (即參數物件自身定義的屬性,並非指原型鏈上的 <code>enumerable</code> 特性 ) 對應其屬性名稱,根據其屬性敘述元 (property descriptors) 加進新創建的物件。這些屬性對應到 {{jsxref("Object.defineProperties()")}} 的第二個參數。</dd> +</dl> + +<h3 id="回傳">回傳</h3> + +<p>具有指定原型物件與屬性的新物件。</p> + +<h3 id="例外">例外</h3> + +<p> 如果 <code>proto</code> 參數不是 {{jsxref("null")}} 或一個物件,將會拋出 {{jsxref("TypeError")}} 例外。</p> + +<h2 id="範例">範例</h2> + +<h3 id="使用_Object.create()_實現類別繼承">使用 <code>Object.create() </code>實現類別繼承</h3> + +<p>下方是如何使用 <code>Object.create()</code> 去實現類別繼承的示範,此為 JavaScript 支援的單一繼承.。</p> + +<pre class="brush: js">// Shape - 父類別 +function Shape() { + this.x = 0; + this.y = 0; +} + +// 父類別的方法 +Shape.prototype.move = function(x, y) { + this.x += x; + this.y += y; + console.info('Shape moved.'); +}; + +// Rectangle - 子類別 +function Rectangle() { + Shape.call(this); // call super constructor. +} + +// 子類別擴展(extends)父類別 +Rectangle.prototype = Object.create(Shape.prototype); +Rectangle.prototype.constructor = Rectangle; + +var rect = new Rectangle(); + +console.log('Is rect an instance of Rectangle?', rect instanceof Rectangle);// true +console.log('Is rect an instance of Shape?', rect instanceof Shape);// true +rect.move(1, 1); // Outputs, 'Shape moved.' +</pre> + +<p>也可像 mixin 繼承多個物件。</p> + +<pre class="brush: js">function MyClass() { + SuperClass.call(this); + OtherSuperClass.call(this); +} + +// 繼承一個父類別 +MyClass.prototype = Object.create(SuperClass.prototype); +// mixin另一個父類別 +Object.assign(MyClass.prototype, OtherSuperClass.prototype); +// 重新指定建構式 +MyClass.prototype.constructor = MyClass; + +MyClass.prototype.myMethod = function() { + // do a thing +}; +</pre> + +<p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign">Object.assign</a> 複製 OtherSuperClass 原型上的所有屬性到 MyClass 的原型上,使所有 MyClass 的實例都能使用。Object.assign 為 ES2015 標準且<a href="https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Object/assign#Polyfill">有 polyfill</a>。如需支援較舊的瀏覽器,可使用第三方套件實現如 <a href="https://api.jquery.com/jQuery.extend/">jQuery.extend()</a> 或 <a href="https://lodash.com/docs/#assign">_.assign()</a> 。</p> + +<h3 id="propertiesObject_參數的使用"><code>propertiesObject</code> 參數的使用</h3> + +<pre class="brush: js">var o; + +// 建立以null為原型的物件 +o = Object.create(null); + + +o = {}; +// 等同於: +o = Object.create(Object.prototype); + + +// Example where we create an object with a couple of sample properties. +// (Note that the second parameter maps keys to *property descriptors*.) +o = Object.create(Object.prototype, { + // foo 為數值屬性 + foo: { writable: true, configurable: true, value: 'hello' }, + // bar 為 getter-and-setter 訪問屬性 + bar: { + configurable: false, + get: function() { return 10; }, + set: function(value) { console.log('Setting `o.bar` to', value); } +/* with ES5 Accessors our code can look like this + get function() { return 10; }, + set function(value) { console.log('setting `o.bar` to', value); } */ + } +}); + + +function Constructor() {} +o = new Constructor(); +// 等同於: +o = Object.create(Constructor.prototype); +// Of course, if there is actual initialization code in the +// Constructor function, the Object.create() cannot reflect it + + +// 創建一個新物件,指定原型是全新的空物件,並加入值為 42 的屬性'p' +o = Object.create({}, { p: { value: 42 } }); + +// 屬性敘述元 writable, enumerable , configurable 未定義,預設皆為 false +o.p = 24; +o.p; +// 42 + +o.q = 12; +for (var prop in o) { + console.log(prop); +} +// 'q' + +delete o.p; +// false + +// to specify an ES3 property +o2 = Object.create({}, { + p: { + value: 42, + writable: true, + enumerable: true, + configurable: true + } +}); +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p>此 polyfill 涵蓋了主要的使用情境:指定一個原型創建一個新的物件,第二個參數為選用。</p> + +<p>要注意的是在 ES5 的<code>Object.create</code>中, <code>[[Prototype]]</code> 可以為 <code>null</code>,但在ECMAScript 5 以前的版本,polyfill 會因為繼承限制( limitation inherent )而不支援此情形。</p> + +<pre><code>if (typeof Object.create !== "function") { + Object.create = function (proto, propertiesObject) { + if (!(proto === null || typeof proto === "object" || typeof proto === "function")) { + throw TypeError('Argument must be an object, or null'); + } + var temp = new Object(); + temp.__proto__ = proto; + if(typeof propertiesObject === "object") + Object.defineProperties(temp, propertiesObject); + return temp; + }; +}</code></pre> + +<h2 id="規範">規範</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.2.3.5', 'Object.create')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.8.5.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object.create', 'Object.create')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-object.create', 'Object.create')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome("5")}}</td> + <td>{{CompatGeckoDesktop("2")}}</td> + <td>{{CompatIE("9")}}</td> + <td>{{CompatOpera("11.60")}}</td> + <td>{{CompatSafari("5")}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</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>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("2")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatOperaMobile("11.5")}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="參閱">參閱</h2> + +<ul> + <li>{{jsxref("Object.defineProperty()")}}</li> + <li>{{jsxref("Object.defineProperties()")}}</li> + <li>{{jsxref("Object.prototype.isPrototypeOf()")}}</li> + <li>John Resig's post on <a href="http://ejohn.org/blog/objectgetprototypeof/">getPrototypeOf()</a></li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/object/defineproperties/index.html b/files/zh-tw/web/javascript/reference/global_objects/object/defineproperties/index.html new file mode 100644 index 0000000000..fc87ca0317 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/object/defineproperties/index.html @@ -0,0 +1,224 @@ +--- +title: Object.defineProperties() +slug: Web/JavaScript/Reference/Global_Objects/Object/defineProperties +translation_of: Web/JavaScript/Reference/Global_Objects/Object/defineProperties +--- +<div>{{JSRef}}</div> + +<p><code><strong>Object.defineProperties()</strong></code> 函式可定義新的或是修改已存在的物件屬性,並回傳修改後的物件。</p> + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox"><code>Object.defineProperties(<var>obj</var>, <var>props</var>)</code></pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>obj</code></dt> + <dd>The object on which to define or modify properties.</dd> + <dt><code>props</code></dt> + <dd>An object whose own enumerable properties constitute descriptors for the properties to be defined or modified. Property descriptors present in objects come in two main flavors: data descriptors and accessor descriptors (see {{jsxref("Object.defineProperty()")}} for more details). Descriptors have the following keys:</dd> + <dd> + <dl> + <dt><code>configurable</code></dt> + <dd><code>true</code> if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object.<br> + <strong>預設為 <code>false</code>.</strong></dd> + <dt><code>enumerable</code></dt> + <dd><code>若該屬性設為 true,則該屬性可被物件所列舉。</code><br> + <strong>預設為 <code>false</code>.</strong></dd> + </dl> + + <dl> + <dt><code>value</code></dt> + <dd>The value associated with the property. Can be any valid JavaScript value (number, object, function, etc).<br> + <strong>預設為 {{jsxref("undefined")}}.</strong></dd> + <dt><code>writable</code></dt> + <dd><code>若該屬性為 true</code>,則該屬性可透過{{jsxref("Operators/Assignment_Operators", "賦予運算子", "", 1)}}所改變<br> + <strong>預設為 <code>false</code>.</strong></dd> + </dl> + + <dl> + <dt><code>get</code></dt> + <dd>A function which serves as a getter for the property, or {{jsxref("undefined")}} if there is no getter. The function return will be used as the value of property.<br> + <strong>預設為 {{jsxref("undefined")}}.</strong></dd> + <dt><code>set</code></dt> + <dd>A function which serves as a setter for the property, or {{jsxref("undefined")}} if there is no setter. The function will receive as only argument the new value being assigned to the property.<br> + <strong>預設為 {{jsxref("undefined")}}.</strong></dd> + </dl> + </dd> +</dl> + +<h3 id="回傳值">回傳值</h3> + +<p>The object that was passed to the function.</p> + +<h2 id="描述">描述</h2> + +<p><code>Object.defineProperties</code>, in essence, defines all properties corresponding to the enumerable own properties of <code>props</code> on the object <code>obj</code> object.</p> + +<h2 id="範例">範例</h2> + +<pre class="brush: js">var obj = {}; +Object.defineProperties(obj, { + 'property1': { + value: true, + writable: true + }, + 'property2': { + value: 'Hello', + writable: false + } + // etc. etc. +}); +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p>Assuming a pristine execution environment with all names and properties referring to their initial values, <code>Object.defineProperties</code> is almost completely equivalent (note the comment in <code>isCallable</code>) to the following reimplementation in JavaScript:</p> + +<pre class="brush: js;highlight:[8]">function defineProperties(obj, properties) { + function convertToDescriptor(desc) { + function hasProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); + } + + function isCallable(v) { + // NB: modify as necessary if other values than functions are callable. + return typeof v === 'function'; + } + + if (typeof desc !== 'object' || desc === null) + throw new TypeError('bad desc'); + + var d = {}; + + if (hasProperty(desc, 'enumerable')) + d.enumerable = !!desc.enumerable; + if (hasProperty(desc, 'configurable')) + d.configurable = !!desc.configurable; + if (hasProperty(desc, 'value')) + d.value = desc.value; + if (hasProperty(desc, 'writable')) + d.writable = !!desc.writable; + if (hasProperty(desc, 'get')) { + var g = desc.get; + + if (!isCallable(g) && typeof g !== 'undefined') + throw new TypeError('bad get'); + d.get = g; + } + if (hasProperty(desc, 'set')) { + var s = desc.set; + if (!isCallable(s) && typeof s !== 'undefined') + throw new TypeError('bad set'); + d.set = s; + } + + if (('get' in d || 'set' in d) && ('value' in d || 'writable' in d)) + throw new TypeError('identity-confused descriptor'); + + return d; + } + + if (typeof obj !== 'object' || obj === null) + throw new TypeError('bad obj'); + + properties = Object(properties); + + var keys = Object.keys(properties); + var descs = []; + + for (var i = 0; i < keys.length; i++) + descs.push([keys[i], convertToDescriptor(properties[keys[i]])]); + + for (var i = 0; i < descs.length; i++) + Object.defineProperty(obj, descs[i][0], descs[i][1]); + + return obj; +} +</pre> + +<h2 id="規格">規格</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">註記</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.2.3.7', 'Object.defineProperties')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.8.5</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object.defineproperties', 'Object.defineProperties')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-object.defineproperties', 'Object.defineProperties')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Firefox (Gecko)</th> + <th>Chrome</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatGeckoDesktop("2")}}</td> + <td>{{CompatChrome("5")}}</td> + <td>{{CompatIE("9")}}</td> + <td>{{CompatOpera("11.60")}}</td> + <td>{{CompatSafari("5")}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Firefox Mobile (Gecko)</th> + <th>Android</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatGeckoMobile("2")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatOperaMobile("11.5")}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="參閱">參閱</h2> + +<ul> + <li>{{jsxref("Object.defineProperty()")}}</li> + <li>{{jsxref("Object.keys()")}}</li> + <li><a href="/en-US/docs/Enumerability_and_ownership_of_properties">Enumerability and ownership of properties</a></li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/object/defineproperty/index.html b/files/zh-tw/web/javascript/reference/global_objects/object/defineproperty/index.html new file mode 100644 index 0000000000..cf83590181 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/object/defineproperty/index.html @@ -0,0 +1,380 @@ +--- +title: Object.defineProperty() +slug: Web/JavaScript/Reference/Global_Objects/Object/defineProperty +translation_of: Web/JavaScript/Reference/Global_Objects/Object/defineProperty +--- +<div>{{JSRef}}</div> + +<p>靜態方法 <code><strong>Object.defineProperty()</strong></code> 會直接對一個物件定義、或是修改現有的屬性。執行後會回傳定義完的物件。</p> + +<div class="note"> +<p><strong>注:</strong>這個方法會直接針對 {{jsxref("Object")}} 呼叫建構子(constructor),而不是 <code>Object</code> 型別的實例。</p> +</div> + +<div>{{EmbedInteractiveExample("pages/js/object-defineproperty.html")}}</div> + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox"><code>Object.defineProperty(<var>obj</var>, <var>prop</var>, <var>descriptor</var>)</code></pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>obj</code></dt> + <dd>要定義屬性的物件。</dd> + <dt><code>prop</code></dt> + <dd>要被定義或修改的屬性名字。</dd> + <dt><code>descriptor</code></dt> + <dd>要定義或修改物件敘述內容。</dd> +</dl> + +<h3 id="回傳值">回傳值</h3> + +<p>被定義完或修改完屬性的物件。</p> + +<h2 id="描述">描述</h2> + +<p>這個函式可以用來增加或修改物件中的屬性定義。在物件建立屬性後,這些屬性同時有被設定預設的設定,才能讓這些屬性被列舉、改變和刪除。而這個函式可以用來改變這些預設的設定。根據預設,被加到物件且使用<code>Object.defineProperty()</code>的值都是{{glossary("Immutable")}}。</p> + +<p>物件內的屬性描述器(Property descriptor)主要有兩種:資料描述器(data descriptor)與訪問描述器(accessor descriptor)。<dfn>資料描述器</dfn>(data descriptor)是可以選擇能否覆寫的屬性。<dfn>訪問描述器</dfn>(accessor descriptor) is a property described by a getter-setter pair of functions. A descriptor must be one of these two flavors; it cannot be both.</p> + +<p>data 和 accessor descriptors 皆為物件,兩者共享下面提及的 key:</p> + +<dl> + <dt><code>configurable</code></dt> + <dd><code>true</code> 則若且唯若此屬性則將可改變或刪除自相應物件。<br> + <strong>預設為 <code>false</code></strong></dd> + <dt><code>enumerable</code></dt> + <dd><code>true</code> 如果且唯若相應物件被列舉,將會列舉此屬性。<br> + <strong>預設為 <code>false</code></strong></dd> +</dl> + +<p>一個 data descriptor 還有以下可選的 key:</p> + +<dl> + <dt><code>value</code></dt> + <dd>The value associated with the property. Can be any valid JavaScript value (number, object, function, etc).<br> + <strong>預設 {{jsxref("undefined")}}.</strong></dd> + <dt><code>writable</code></dt> + <dd><code>true</code> 則該物件屬性可透過{{jsxref("Operators/Assignment_Operators", "賦予運算子", "", 1)}}改變其值。<br> + <strong>預設 <code>false</code></strong></dd> +</dl> + +<p>一個 accessor descriptor 也擁有下述之 optional keys:</p> + +<dl> + <dt><code>get</code></dt> + <dd>作為 getter 形式,為屬性存在的函式,如果沒有 getter 的話則回傳 {{jsxref("undefined")}}。函式回傳將用於屬性值。<br> + <strong>預設 {{jsxref("undefined")}}</strong></dd> + <dt><code>set</code></dt> + <dd>作為 setter 形式,為屬性存在的函式,如果沒有 setter 的話則回傳 {{jsxref("undefined")}}。 The function will receive as only argument the new value being assigned to the property.<br> + <strong>預設 {{jsxref("undefined")}}</strong></dd> +</dl> + +<p>請注意,這些選項並不一定要是 descriptor 屬性,由原型鍊(prototype chain)繼承的屬性,也會被考慮到。要確保需要凍結(freeze)的 {{jsxref("Object.prototype")}} upfront 預設能被保存,請明確指定所有選項,或把 {{jsxref("Object.prototype.__proto__", "__proto__")}} 屬性指向 {{jsxref("null")}}。</p> + +<pre class="brush: js">// using __proto__ +var obj = {}; +Object.defineProperty(obj, 'key', { + __proto__: null, // no inherited properties + value: 'static' // not enumerable + // not configurable + // not writable + // as defaults +}); + +// being explicit +Object.defineProperty(obj, 'key', { + enumerable: false, + configurable: false, + writable: false, + value: 'static' +}); + +// recycling same object +function withValue(value) { + var d = withValue.d || ( + withValue.d = { + enumerable: false, + writable: false, + configurable: false, + value: null + } + ); + d.value = value; + return d; +} +// ... and ... +Object.defineProperty(obj, 'key', withValue('static')); + +// if freeze is available, prevents adding or +// removing the object prototype properties +// (value, get, set, enumerable, writable, configurable) +(Object.freeze || Object)(Object.prototype); +</pre> + +<h2 id="範例">範例</h2> + +<p>If you want to see how to use the <code>Object.defineProperty</code> method with a <em>binary-flags-like</em> syntax, see <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty/Additional_examples">additional examples</a>.</p> + +<h3 id="建立屬性">建立屬性</h3> + +<p>When the property specified doesn't exist in the object, <code>Object.defineProperty()</code> creates a new property as described. Fields may be omitted from the descriptor, and default values for those fields are imputed. All of the Boolean-valued fields default to <code>false</code>. The <code>value</code>, <code>get</code>, and <code>set</code> fields default to {{jsxref("undefined")}}. A property which is defined without <code>get</code>/<code>set</code>/<code>value</code>/<code>writable</code> is called “generic” and is “typed” as a data descriptor.</p> + +<pre class="brush: js">var o = {}; // Creates a new object + +// Example of an object property added with defineProperty with a data property descriptor +Object.defineProperty(o, 'a', { + value: 37, + writable: true, + enumerable: true, + configurable: true +}); +// 'a' property exists in the o object and its value is 37 + +// Example of an object property added with defineProperty with an accessor property descriptor +var bValue = 38; +Object.defineProperty(o, 'b', { + get: function() { return bValue; }, + set: function(newValue) { bValue = newValue; }, + enumerable: true, + configurable: true +}); +o.b; // 38 +// 'b' property exists in the o object and its value is 38 +// The value of o.b is now always identical to bValue, unless o.b is redefined + +// You cannot try to mix both: +Object.defineProperty(o, 'conflict', { + value: 0x9f91102, + get: function() { return 0xdeadbeef; } +}); +// throws a TypeError: value appears only in data descriptors, get appears only in accessor descriptors +</pre> + +<h3 id="修改屬性">修改屬性</h3> + +<p>如果該屬性已經存在, <code>Object.defineProperty()</code> 將會根據描述符內的值和物件當前的 configuration 來修改屬性。 如果舊的描述符之 <code>configurable</code> 的特徵為 false (屬性為 “non-configurable”), 那除了 <code>writable</code> 之外的特徵都將無法修改。 在這個情況,也不可能在 data 和 accessor 屬性類型中來回切換。</p> + +<p>如果有一個屬性是 non-configurable, 那它的 <code>writable</code> 特徵只能被改變為 <font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">false</span></font>.</p> + +<p>若嘗試改變 non-configurable property attributes,將會丟出一個 {{jsxref("TypeError")}},除非當前之值與新值相同。</p> + +<h4 id="Writable_attribute">Writable attribute</h4> + +<p>當 <code>writable</code> 屬性特徵被設為 <code>false</code>, 此屬性為 “non-writable”. 它將無法被重新賦值。</p> + +<pre class="brush: js">var o = {}; // Creates a new object + +Object.defineProperty(o, 'a', { + value: 37, + writable: false +}); + +console.log(o.a); // logs 37 +o.a = 25; // No error thrown (it would throw in strict mode, even if the value had been the same) +console.log(o.a); // logs 37. The assignment didn't work. +</pre> + +<p>As seen in the example, trying to write into the non-writable property doesn't change it but doesn't throw an error either.</p> + +<h4 id="可列舉_attribute">可列舉 attribute</h4> + +<p>The <code>enumerable</code> property attribute defines whether the property shows up in a {{jsxref("Statements/for...in", "for...in")}} loop and {{jsxref("Object.keys()")}} or not.</p> + +<pre class="brush: js">var o = {}; +Object.defineProperty(o, 'a', { value: 1, enumerable: true }); +Object.defineProperty(o, 'b', { value: 2, enumerable: false }); +Object.defineProperty(o, 'c', { value: 3 }); // enumerable defaults to false +o.d = 4; // enumerable defaults to true when creating a property by setting it + +for (var i in o) { + console.log(i); +} +// logs 'a' and 'd' (in undefined order) + +Object.keys(o); // ['a', 'd'] + +o.propertyIsEnumerable('a'); // true +o.propertyIsEnumerable('b'); // false +o.propertyIsEnumerable('c'); // false +</pre> + +<h4 id="可設定_attribute">可設定 attribute</h4> + +<p>The <code>configurable</code> attribute controls at the same time whether the property can be deleted from the object and whether its attributes (other than <code>writable</code>) can be changed.</p> + +<pre class="brush: js">var o = {}; +Object.defineProperty(o, 'a', { + get: function() { return 1; }, + configurable: false +}); + +Object.defineProperty(o, 'a', { configurable: true }); // throws a TypeError +Object.defineProperty(o, 'a', { enumerable: true }); // throws a TypeError +Object.defineProperty(o, 'a', { set: function() {} }); // throws a TypeError (set was undefined previously) +Object.defineProperty(o, 'a', { get: function() { return 1; } }); // throws a TypeError (even though the new get does exactly the same thing) +Object.defineProperty(o, 'a', { value: 12 }); // throws a TypeError + +console.log(o.a); // logs 1 +delete o.a; // Nothing happens +console.log(o.a); // logs 1 +</pre> + +<p>If the <code>configurable</code> attribute of <code>o.a</code> had been <code>true</code>, none of the errors would be thrown and the property would be deleted at the end.</p> + +<h3 id="新增多個屬性及賦予初始值">新增多個屬性及賦予初始值</h3> + +<p>It's important to consider the way default values of attributes are applied. There is often a difference between simply using dot notation to assign a value and using <code>Object.defineProperty()</code>, as shown in the example below.</p> + +<pre class="brush: js">var o = {}; + +o.a = 1; +// is equivalent to: +Object.defineProperty(o, 'a', { + value: 1, + writable: true, + configurable: true, + enumerable: true +}); + + +// On the other hand, +Object.defineProperty(o, 'a', { value: 1 }); +// is equivalent to: +Object.defineProperty(o, 'a', { + value: 1, + writable: false, + configurable: false, + enumerable: false +}); +</pre> + +<h3 id="Custom_Setters_and_Getters">Custom Setters and Getters</h3> + +<p>Example below shows how to implement a self-archiving object. When <code>temperature</code> property is set, the <code>archive</code> array gets a log entry.</p> + +<pre class="brush: js">function Archiver() { + var temperature = null; + var archive = []; + + Object.defineProperty(this, 'temperature', { + get: function() { + console.log('get!'); + return temperature; + }, + set: function(value) { + temperature = value; + archive.push({ val: temperature }); + } + }); + + this.getArchive = function() { return archive; }; +} + +var arc = new Archiver(); +arc.temperature; // 'get!' +arc.temperature = 11; +arc.temperature = 13; +arc.getArchive(); // [{ val: 11 }, { val: 13 }] +</pre> + +<p>or</p> + +<pre class="brush: js">var pattern = { + get: function () { + return 'I always return this string, whatever you have assigned'; + }, + set: function () { + this.myname = 'this is my name string'; + } +}; + + +function TestDefineSetAndGet() { + Object.defineProperty(this, 'myproperty', pattern); +} + + +var instance = new TestDefineSetAndGet(); +instance.myproperty = 'test'; +console.log(instance.myproperty); // I always return this string, whatever you have assigned + +console.log(instance.myname); // this is my name string + +</pre> + +<h2 id="規格">規格</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">註記</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.2.3.6', 'Object.defineProperty')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.8.5.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object.defineproperty', 'Object.defineProperty')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-object.defineproperty', 'Object.defineProperty')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Object.defineProperty")}}</p> +</div> + +<h2 id="Compatibility_notes">Compatibility notes</h2> + +<h3 id="Redefining_the_length_property_of_an_Array_object">Redefining the <code>length</code> property of an <code>Array</code> object</h3> + +<p>It is possible to redefine the {{jsxref("Array.length", "length")}} property of arrays, subject to the usual redefinition restrictions. (The {{jsxref("Array.length", "length")}} property is initially non-configurable, non-enumerable, and writable. Thus on an unaltered array, it's possible to change the {{jsxref("Array.length", "length")}} property's value or to make it non-writable. It is not allowed to change its enumerability or configurability, or if it is non-writable to change its value or writability.) However, not all browsers permit this redefinition.</p> + +<p>Firefox 4 through 22 will throw a {{jsxref("TypeError")}} on any attempt whatsoever (whether permitted or not) to redefine the {{jsxref("Array.length", "length")}} property of an array.</p> + +<p>Versions of Chrome which implement <code>Object.defineProperty()</code> in some circumstances ignore a length value different from the array's current {{jsxref("Array.length", "length")}} property. In some circumstances changing writability seems to silently not work (and not throw an exception). Also, relatedly, some array-mutating methods like {{jsxref("Array.prototype.push")}} don't respect a non-writable length.</p> + +<p>Versions of Safari which implement <code>Object.defineProperty()</code> ignore a <code>length</code> value different from the array's current {{jsxref("Array.length", "length")}} property, and attempts to change writability execute without error but do not actually change the property's writability.</p> + +<p>Only Internet Explorer 9 and later, and Firefox 23 and later, appear to fully and correctly implement redefinition of the {{jsxref("Array.length", "length")}} property of arrays. For now, don't rely on redefining the {{jsxref("Array.length", "length")}} property of an array to either work, or to work in a particular manner. And even when you <em>can</em> rely on it, <a href="http://whereswalden.com/2013/08/05/new-in-firefox-23-the-length-property-of-an-array-can-be-made-non-writable-but-you-shouldnt-do-it/">there's really no good reason to do so</a>.</p> + +<h3 id="Internet_Explorer_8_specific_notes">Internet Explorer 8 specific notes</h3> + +<p>Internet Explorer 8 implemented a <code>Object.defineProperty()</code> method that could <a class="external" href="https://msdn.microsoft.com/en-us/library/dd229916%28VS.85%29.aspx">only be used on DOM objects</a>. A few things need to be noted:</p> + +<ul> + <li>Trying to use <code>Object.defineProperty()</code> on native objects throws an error.</li> + <li>Property attributes must be set to some values. The <code>configurable</code>, <code>enumerable</code> and <code>writable</code> attributes should all be set to <code>true</code> for data descriptor and <code>true</code> for <code>configurable</code>, <code>false</code> for <code>enumerable</code> for accessor descriptor.(?) Any attempt to provide other value(?) will result in an error being thrown.</li> + <li>Reconfiguring a property requires first deleting the property. If the property isn't deleted, it stays as it was before the reconfiguration attempt.</li> +</ul> + +<h2 id="參閱">參閱</h2> + +<ul> + <li><a href="/zh-TW/docs/Enumerability_and_ownership_of_properties">Enumerability and ownership of properties</a></li> + <li>{{jsxref("Object.defineProperties()")}}</li> + <li>{{jsxref("Object.propertyIsEnumerable()")}}</li> + <li>{{jsxref("Object.getOwnPropertyDescriptor()")}}</li> + <li>{{jsxref("Object.prototype.watch()")}}</li> + <li>{{jsxref("Object.prototype.unwatch()")}}</li> + <li>{{jsxref("Operators/get", "get")}}</li> + <li>{{jsxref("Operators/set", "set")}}</li> + <li>{{jsxref("Object.create()")}}</li> + <li><a href="/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty/Additional_examples">Additional <code>Object.defineProperty</code> examples</a></li> + <li>{{jsxref("Reflect.defineProperty()")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/object/freeze/index.html b/files/zh-tw/web/javascript/reference/global_objects/object/freeze/index.html new file mode 100644 index 0000000000..0c26b9f308 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/object/freeze/index.html @@ -0,0 +1,198 @@ +--- +title: Object.freeze() +slug: Web/JavaScript/Reference/Global_Objects/Object/freeze +translation_of: Web/JavaScript/Reference/Global_Objects/Object/freeze +--- +<div>{{JSRef}}</div> + +<p> </p> + +<p><code><strong>Object.freeze()</strong></code> 顧名思義是用來「凍結」一個物件的: 也就是防止物件新增屬性; 防止物件既有的屬性被刪除; 防止物件原本的屬性, 還有屬性的可列舉性, 可設定性, 可寫性被改動; 同時它也防止物件的原型被改變。此方法回傳一個凍結狀態的物件。</p> + +<div>{{EmbedInteractiveExample("pages/js/object-freeze.html")}}</div> + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox"><code>Object.freeze(<var>obj</var>)</code></pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>obj</code></dt> + <dd>要被凍結的物件</dd> +</dl> + +<h3 id="回傳值">回傳值</h3> + +<p>被凍結的物件</p> + +<h2 id="描述">描述</h2> + +<p>一個被凍結的物件無法被新增或刪除屬性。任何想要改動的嘗試都會失敗, 要不沈默地失敗, 就是丟出一個 {{jsxref("TypeError")}} 例外 (此例外最常出現在 {{jsxref("Strict_mode", "strict mode", "", 1)}})</p> + +<p>資料屬性無法被改變。訪問者方法 - setters 也一樣不能改變資料屬性 (雖然它會給你可以改變資料值的假象)。注意! 如果資料屬性是物件的話,該物件的值是可以被改變的,除非它們也被凍結。一個陣列同樣可以被凍結 (因為它也是一個物件),被凍結後它的元素內容就不能被改變,也不能新增或刪除元素。</p> + +<h2 id="範例">範例</h2> + +<h3 id="凍結物件">凍結物件</h3> + +<pre class="brush: js">var obj = { + prop: function() {}, + foo: 'bar' +}; + +// 新的屬性可以被新增,原本的屬性可以被改變或刪除 +obj.foo = 'baz'; +obj.lumpy = 'woof'; +delete obj.prop; + +// 回傳的物件跟原本傳入的物件是同一個,所以不需要記住回傳值 +// 也可以凍結一個物件 +var o = Object.freeze(obj); + +o === obj; // true +Object.isFrozen(obj); // === true + +// 現在任何改動都會失敗 +obj.foo = 'quux'; // 什麼事也不會發生 +// 屬性無法被新增 +obj.quaxxor = 'the friendly duck'; + +// 在嚴格模式中,如方才的嘗試都會丟出 TypeError +function fail(){ + 'use strict'; + obj.foo = 'sparky'; // 丟出 TypeError + delete obj.foo; // 丟出 TypeError + delete obj.quaxxor; // 回傳 true 因為屬性 'quaxxor' 從來沒有被新增 + obj.sparky = 'arf'; // 丟出 TypeError +} + +fail(); + +// 嘗試透過 Object.defineProperty 來改變屬性的值會丟出 TypeError +Object.defineProperty(obj, 'ohai', { value: 17 }); +Object.defineProperty(obj, 'foo', { value: 'eit' }); + +// 一樣不可能改變物件的原型,都會丟出 TypeError +Object.setPrototypeOf(obj, { x: 20 }) +obj.__proto__ = { x: 20 } +</pre> + +<h3 id="凍結陣列">凍結陣列</h3> + +<pre>let a = [0]; +Object.freeze(a); // 現在這個陣列不能被改動 + +a[0]=1; // 沈默地失敗 +a.push(2); // 沈默地失敗 + +// 在嚴格模式底下會丟出 TypeError +function fail() { + "use strict" + a[0] = 1; + a.push(2); +} + +fail();</pre> + +<p>被凍結的物件是<em>不可變 (Immutable) </em>的。然而,它並不等於常數<em> (constant)</em>。以下的範例顯示一個被凍結的物件並不是常數 (凍結的動作是「淺」的 - 如果資料屬性也是物件, 不會遞迴地做凍結的動作)。</p> + +<pre class="brush: js">obj1 = { + internal: {} +}; + +Object.freeze(obj1); +obj1.internal.a = 'aValue'; + +obj1.internal.a // 'aValue'</pre> + +<p class="brush: js">如果要成為一個常數物件,整個物件參考圖 (包含直接指向或間接指向其他物件) 必須都只能指向被凍結的不可變物件。一個物件被稱作不可變是因為它的整個物件狀態 (值或是指向其他物件的參考) 是固定的。注意,string, number 和 boolean 這些原始型別的值是永遠不變的,Function 和 Array 都屬於物件的一種。</p> + +<p class="brush: js">要讓一個物件變成常數物件,就必須遞迴地凍結每個是物件型別的屬性 (稱作深凍結)。只有當你知道物件的參考圖不存在任何<em><a href="https://en.wikipedia.org/wiki/Cycle_(graph_theory)">循環</a> </em>的時候才能使用以上遞迴的方式來凍結物件,不然就可能會造成無窮迴圈。一個改善以下範例中 deepFreeze() 來解決無窮迴圈問題的方法是 - 創建一個接受一個路徑參數 (像是陣列) 的內部用函數,用來避免無窮遞迴地呼叫 deepFreeze() - 當發現欲凍結的物件已經出現在之前凍結的物件行列中就不繼續遞迴下去。需要注意的是你可能會不小心凍結一個不應該被凍結的物件,像是 [window]。</p> + +<pre class="brush: js">// 用這個函數來進行對物件的深凍結 +function deepFreeze(obj) { + + // 取得物件的所有屬性名稱 + var propNames = Object.getOwnPropertyNames(obj); + + // 在凍結物件本身之前先凍結物件的所有物件屬性 + propNames.forEach(function(name) { + var prop = obj[name]; + + // 凍結 prop 如果它是一個物件 + if (typeof prop == 'object' && prop !== null) + deepFreeze(prop); + }); + + // 凍結本身 (no-op 如果已經被凍結了) + return Object.freeze(obj); +} + +obj2 = { + internal: {} +}; + +deepFreeze(obj2); +obj2.internal.a = 'anotherValue'; +obj2.internal.a; // undefined</pre> + +<h2 id="備註">備註</h2> + +<p>在 ES5 中,如果傳入此方法的參數不是一個物件 (原始型別),{{jsxref("TypeError")}} 就會被丟出。而在 ES2015,一個非物件型態的參數會被當成是一個已經被凍結的物件,所以會被直接回傳?不會造成錯誤。</p> + +<pre class="brush: js">> Object.freeze(1) +TypeError: 1 is not an object // ES5 code + +> Object.freeze(1) +1 // ES2015 code +</pre> + +<h3 id="與_Object.seal()_的差別">與 <code>Object.seal()</code> 的差別</h3> + +<p>被 <code>Object.seal()</code> 密封的物件還是可以改變它原有屬性的值。而被 <code>Object.freeze()</code> 凍結的物件則無法改變它原有屬性的值因為他們是不可變的。</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('ES5.1', '#sec-15.2.3.9', 'Object.freeze')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>第一版。實作於 JavaScript 1.8.5.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object.freeze', 'Object.freeze')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-object.freeze', 'Object.freeze')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Object.freeze")}}</p> +</div> + +<h2 id="參閱">參閱</h2> + +<ul> + <li>{{jsxref("Object.isFrozen()")}}</li> + <li>{{jsxref("Object.preventExtensions()")}}</li> + <li>{{jsxref("Object.isExtensible()")}}</li> + <li>{{jsxref("Object.seal()")}}</li> + <li>{{jsxref("Object.isSealed()")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/object/getprototypeof/index.html b/files/zh-tw/web/javascript/reference/global_objects/object/getprototypeof/index.html new file mode 100644 index 0000000000..ff4e4d480f --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/object/getprototypeof/index.html @@ -0,0 +1,128 @@ +--- +title: Object.getPrototypeOf() +slug: Web/JavaScript/Reference/Global_Objects/Object/getPrototypeOf +tags: + - JavaScript + - Method + - Object +translation_of: Web/JavaScript/Reference/Global_Objects/Object/getPrototypeOf +--- +<div>{{JSRef}}</div> + +<p><code><strong>Object.getPrototypeOf()</strong></code> 回傳指定物件的原型,換句話說,就是取得該物件的 <code>[[Prototype]]</code> 屬性的值).</p> + +<h2 id="表達式">表達式</h2> + +<pre class="syntaxbox"><code>Object.getPrototypeOf(<var>obj</var>)</code></pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>obj</code></dt> + <dd>欲取得原型的物件。</dd> +</dl> + +<h2 id="範例">範例</h2> + +<pre class="brush: js">var proto = {}; +var obj = Object.create(proto); +Object.getPrototypeOf(obj) === proto; // true +</pre> + +<h2 id="備註">備註</h2> + +<p>如果 <code>obj</code> 參數在 ES5 並不是物件時會拋出 {{jsxref("TypeError")}} 例外,同樣狀況在 ES6 時該參數將會被強制轉換成 {{jsxref("Object")}}。</p> + +<pre class="brush: js">Object.getPrototypeOf("foo"); +// TypeError: "foo" is not an object (ES5 code) +Object.getPrototypeOf("foo"); +// String.prototype (ES6 code) +</pre> + +<h2 id="規範">規範</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.2.3.2', 'Object.getPrototypeOf')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object.getprototypeof', 'Object.getProtoypeOf')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome("5")}}</td> + <td>{{CompatGeckoDesktop("1.9.1")}}</td> + <td>{{CompatIE("9")}}</td> + <td>{{CompatOpera("12.10")}}</td> + <td>{{CompatSafari("5")}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</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>Basic support</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Opera_註">Opera 註</h2> + +<p>雖然舊版的 Opera 並不支援 <code>Object.getPrototypeOf()</code>,但是 Opera 從 Opera 10.50 支援非標準的 {{jsxref("Object.proto", "__proto__")}} 屬性。</p> + +<h2 id="參見">參見</h2> + +<ul> + <li>{{jsxref("Object.prototype.isPrototypeOf()")}}</li> + <li>{{jsxref("Object.setPrototypeOf()")}} {{experimental_inline}}</li> + <li>{{jsxref("Object.prototype.__proto__")}}</li> + <li>John Resig 的文章--《 <a class="external" href="http://ejohn.org/blog/objectgetprototypeof/">getPrototypeOf</a> 》</li> + <li>{{jsxref("Reflect.getPrototypeOf()")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/object/hasownproperty/index.html b/files/zh-tw/web/javascript/reference/global_objects/object/hasownproperty/index.html new file mode 100644 index 0000000000..1786387141 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/object/hasownproperty/index.html @@ -0,0 +1,184 @@ +--- +title: Object.prototype.hasOwnProperty() +slug: Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty +tags: + - JavaScript +translation_of: Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty +--- +<div>{{JSRef}}</div> + +<p><code><strong>hasOwnProperty()</strong></code> 回傳物件是否有該屬性的布林值。</p> + +<h2 id="表達式">表達式</h2> + +<pre class="syntaxbox"><code><var>obj</var>.hasOwnProperty(<var>prop</var>)</code></pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>prop</code></dt> + <dd>屬性名稱。</dd> +</dl> + +<h2 id="說明">說明</h2> + +<p>每個為 {{jsxref("Object")}} 後代的物件都繼承 <code>hasOwnProperty</code> 方法。這個方法可以被使用來決定物件是否擁有特定的直接屬性;跟 {{jsxref("Operators/in", "in")}} 不一樣,這個方法並未檢查物件的原型鏈。</p> + +<h2 id="範例">範例</h2> + +<h3 id="使用_hasOwnProperty_測試屬性是否存在">使用 <code>hasOwnProperty</code> 測試屬性是否存在</h3> + +<p>這個範例顯示 <code>o </code>物件是否擁有名為 <code>prop </code>的屬性:</p> + +<pre class="brush: js">o = new Object(); +o.prop = 'exists'; + +function changeO() { + o.newprop = o.prop; + delete o.prop; +} + +o.hasOwnProperty('prop'); // 回傳 true +changeO(); +o.hasOwnProperty('prop'); // 回傳 false +</pre> + +<h3 id="直接與繼承的屬性">直接與繼承的屬性</h3> + +<p>這個範例區分直接屬性和從原型鍊繼承的屬性:</p> + +<pre class="brush: js">o = new Object(); +o.prop = 'exists'; +o.hasOwnProperty('prop'); // 回傳 true +o.hasOwnProperty('toString'); // 回傳 false +o.hasOwnProperty('hasOwnProperty'); // 回傳 false +</pre> + +<h3 id="遍歷物件的屬性">遍歷物件的屬性</h3> + +<p>這個範例顯示如何不執行繼承的屬性去遍歷物件的屬性。注意 {{jsxref("Statements/for...in", "for...in")}} 已經遍歷了可以被列舉的項目,所以不該基於缺乏不可列舉的屬性(如下)而假設 <code>hasOwnProperty</code> 被嚴格地限制在列舉的項目(如同 {{jsxref("Object.getOwnPropertyNames()")}})。</p> + +<pre class="brush: js">var buz = { + fog: 'stack' +}; + +for (var name in buz) { + if (buz.hasOwnProperty(name)) { + console.log('this is fog (' + name + ') for sure. Value: ' + buz[name]); + } + else { + console.log(name); // toString or something else + } +} +</pre> + +<h3 id="將_hasOwnProperty_作為屬性"><code>將 hasOwnProperty</code> 作為屬性</h3> + +<p>JavaScript 並未保護 <code>hasOwnProperty</code>;因此,如果一個物件擁有一樣的屬性名稱,為了獲得正確的結果需要使用 <em>external</em> <code>hasOwnProperty</code>:</p> + +<pre class="brush: js">var foo = { + hasOwnProperty: function() { + return false; + }, + bar: 'Here be dragons' +}; + +foo.hasOwnProperty('bar'); // 總是回傳 false + +// 使用其他物件的 hasOwnProperty 和 call it with 'this' set to foo +({}).hasOwnProperty.call(foo, 'bar'); // true + +// 從物件的原型使用 hasOwnProperty 也是可行的 +Object.prototype.hasOwnProperty.call(foo, 'bar'); // true +</pre> + +<p>註:在最後一個例子中並未創建任何新的物件。</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('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Initial definition. Implemented in JavaScript 1.5.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.2.4.5', 'Object.prototype.hasOwnProperty')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object.prototype.hasownproperty', 'Object.prototype.hasOwnProperty')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</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>Feature</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>Basic support</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><a href="/en-US/docs/Enumerability_and_ownership_of_properties">Enumerability and ownership of properties</a></li> + <li>{{jsxref("Object.getOwnPropertyNames()")}}</li> + <li>{{jsxref("Statements/for...in", "for...in")}}</li> + <li>{{jsxref("Operators/in", "in")}}</li> + <li><a href="/en-US/docs/Web/JavaScript/Guide/Inheritance_Revisited">JavaScript Guide: Inheritance revisited</a></li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/object/index.html b/files/zh-tw/web/javascript/reference/global_objects/object/index.html new file mode 100644 index 0000000000..3885c44a15 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/object/index.html @@ -0,0 +1,222 @@ +--- +title: Object +slug: Web/JavaScript/Reference/Global_Objects/Object +tags: + - Constructor + - JavaScript + - NeedsTranslation + - Object + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/Object +--- +<div>{{JSRef}}</div> + +<p><code><strong>Object</strong></code> 建構式可用於建立物件包裝(object wrapper)。</p> + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox notranslate">// Object initialiser or literal +{ [ <var>nameValuePair1</var>[, <var>nameValuePair2</var>[, ...<var>nameValuePairN</var>] ] ] } + +// Called as a constructor +new Object([<var>value</var>])</pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>nameValuePair1, nameValuePair2, ... nameValuePair<em>N</em></code></dt> + <dd>Pairs of names (strings) and values (any value) where the name is separated from the value by a colon.</dd> + <dt><code>value</code></dt> + <dd>任意值。</dd> +</dl> + +<h2 id="描述">描述</h2> + +<p>The <code>Object</code> constructor creates an object wrapper for the given value. If the value is {{jsxref("null")}} or {{jsxref("undefined")}}, it will create and return an empty object, otherwise, it will return an object of a Type that corresponds to the given value. If the value is an object already, it will return the value.</p> + +<p>When called in a non-constructor context, <code>Object</code> behaves identically to <code>new Object()</code>.</p> + +<p>也可以參考 <a href="/zh-TW/docs/Web/JavaScript/Reference/Operators/Object_initializer">object initializer / literal syntax</a>.</p> + +<h2 id="Object_建構式屬性"><code>Object</code> 建構式屬性</h2> + +<dl> + <dt><code>Object.length</code></dt> + <dd>Has a value of 1.</dd> + <dt>{{jsxref("Object.prototype")}}</dt> + <dd>Allows the addition of properties to all objects of type Object.</dd> +</dl> + +<h2 id="Object_建構式方法"><code>Object</code> 建構式方法</h2> + +<dl> + <dt>{{jsxref("Object.assign()")}}</dt> + <dd>Creates a new object by copying the values of all enumerable own properties from one or more source objects to a target object.</dd> + <dt>{{jsxref("Object.create()")}}</dt> + <dd>Creates a new object with the specified prototype object and properties.</dd> + <dt>{{jsxref("Object.defineProperty()")}}</dt> + <dd>Adds the named property described by a given descriptor to an object.</dd> + <dt>{{jsxref("Object.defineProperties()")}}</dt> + <dd>Adds the named properties described by the given descriptors to an object.</dd> + <dt>{{jsxref("Object.entries()")}} {{experimental_inline}}</dt> + <dd>Returns an array of a given object's own enumerable property <code>[key, value]</code> pairs.</dd> + <dt>{{jsxref("Object.freeze()")}}</dt> + <dd>Freezes an object: other code can't delete or change any properties.</dd> + <dt>{{jsxref("Object.getOwnPropertyDescriptor()")}}</dt> + <dd>Returns a property descriptor for a named property on an object.</dd> + <dt>{{jsxref("Object.getOwnPropertyDescriptors()")}}</dt> + <dd>Returns an object containing all own property descriptors for an object.</dd> + <dt>{{jsxref("Object.getOwnPropertyNames()")}}</dt> + <dd>Returns an array containing the names of all of the given object's <strong>own</strong> enumerable and non-enumerable properties.</dd> + <dt>{{jsxref("Object.getOwnPropertySymbols()")}}</dt> + <dd>Returns an array of all symbol properties found directly upon a given object.</dd> + <dt>{{jsxref("Object.getPrototypeOf()")}}</dt> + <dd>Returns the prototype of the specified object.</dd> + <dt>{{jsxref("Object.is()")}}</dt> + <dd>Compares if two values are distinguishable (ie. the same)</dd> + <dt>{{jsxref("Object.isExtensible()")}}</dt> + <dd>Determines if extending of an object is allowed.</dd> + <dt>{{jsxref("Object.isFrozen()")}}</dt> + <dd>Determines if an object was frozen.</dd> + <dt>{{jsxref("Object.isSealed()")}}</dt> + <dd>Determines if an object is sealed.</dd> + <dt>{{jsxref("Object.keys()")}}</dt> + <dd>Returns an array containing the names of all of the given object's <strong>own</strong> enumerable properties.</dd> + <dt>{{jsxref("Object.preventExtensions()")}}</dt> + <dd>Prevents any extensions of an object.</dd> + <dt>{{jsxref("Object.seal()")}}</dt> + <dd>Prevents other code from deleting properties of an object.</dd> + <dt>{{jsxref("Object.setPrototypeOf()")}}</dt> + <dd>Sets the prototype (i.e., the internal <code>[[Prototype]]</code> property)</dd> + <dt>{{jsxref("Object.values()")}} {{experimental_inline}}</dt> + <dd>Returns an array of a given object's own enumerable values.</dd> +</dl> + +<h2 id="Object_物件實體與_Object_原型物件"><code>Object</code> 物件實體與 <code>Object</code> 原型物件</h2> + +<p>All objects in JavaScript are descended from <code>Object</code>; all objects inherit methods and properties from {{jsxref("Object.prototype")}}, although they may be overridden. For example, other constructors' prototypes override the <code>constructor</code> property and provide their own <code>toString()</code> methods. Changes to the <code>Object</code> prototype object are propagated to all objects unless the properties and methods subject to those changes are overridden further along the prototype chain.</p> + +<h3 id="屬性">屬性</h3> + +<div>{{page('/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype', '屬性') }}</div> + +<h3 id="方法">方法</h3> + +<div>{{page('/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype', '方法') }}</div> + +<h2 id="範例">範例</h2> + +<h3 id="Using_Object_given_undefined_and_null_types">Using <code>Object</code> given <code>undefined</code> and <code>null</code> types</h3> + +<p>下面例子儲存一個空物件至變數o</p> + +<pre class="brush: js notranslate">var o = new Object(); +</pre> + +<pre class="brush: js notranslate">var o = new Object(undefined); +</pre> + +<pre class="brush: js notranslate">var o = new Object(null); +</pre> + +<h3 id="Using_Object_to_create_Boolean_objects">Using <code>Object</code> to create <code>Boolean</code> objects</h3> + +<p>下面例子儲存 {{jsxref("Boolean")}} 物件在 <code>o</code>:</p> + +<pre class="brush: js notranslate">// equivalent to o = new Boolean(true); +var o = new Object(true); +</pre> + +<pre class="brush: js notranslate">// equivalent to o = new Boolean(false); +var o = new Object(Boolean()); +</pre> + +<h2 id="規範">規範</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.2', 'Object')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object-objects', 'Object')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Added Object.assign, Object.getOwnPropertySymbols, Object.setPrototypeOf, Object.is</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-object-objects', 'Object')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>Added Object.entries, Object.values and Object.getOwnPropertyDescriptors.</td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</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>Feature</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>Basic support</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><a href="/zh-TW/docs/Web/JavaScript/Reference/Operators/Object_initializer">Object initializer</a></li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/object/keys/index.html b/files/zh-tw/web/javascript/reference/global_objects/object/keys/index.html new file mode 100644 index 0000000000..958b9a3a47 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/object/keys/index.html @@ -0,0 +1,208 @@ +--- +title: Object.keys() +slug: Web/JavaScript/Reference/Global_Objects/Object/keys +tags: + - ECMAScript 5 + - JavaScript +translation_of: Web/JavaScript/Reference/Global_Objects/Object/keys +--- +<div>{{JSRef}}</div> + +<p><code><strong>Object.keys()</strong></code> 方法會回傳一個由指定物件所有可列舉之屬性組成的陣列,該陣列中的的排列順序與使用 {{jsxref("Statements/for...in", "for...in")}} 進行迭代的順序相同(兩者的差異在於 <code>for-in</code> 迴圈還會迭代出物件自其原型鏈所繼承來的可列舉屬性)。</p> + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox"><code>Object.keys(<var>obj</var>)</code></pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>obj</code></dt> + <dd>物件,用以回傳其可列舉屬性。</dd> +</dl> + +<h3 id="回傳值">回傳值</h3> + +<p>回傳一個包含給定物件內所有可列舉屬性的字串陣列。</p> + +<h2 id="描述">描述</h2> + +<p><code>Object.keys()</code> 回傳一個陣列,陣列中的各元素為直屬於 <code>obj</code> ,對應可列舉屬性名的字串。回傳結果的排序,與手動對物件屬性作迴圈迭代的結果排序相同。</p> + +<h2 id="範例">範例</h2> + +<pre class="brush: js">var arr = ['a', 'b', 'c']; +console.log(Object.keys(arr)); // console: ['0', '1', '2'] + +// 類似陣列的物件 +var obj = { 0: 'a', 1: 'b', 2: 'c' }; +console.log(Object.keys(obj)); // console: ['0', '1', '2'] + +// 擁有隨機 key 排序,類似陣列的物件 +var an_obj = { 100: 'a', 2: 'b', 7: 'c' }; +console.log(Object.keys(an_obj)); // console: ['2', '7', '100'] + +// getFoo 不是可列舉的屬性 +var my_obj = Object.create({}, { + getFoo: { + value: function() { return this.foo; } + } +}); +my_obj.foo = 1; + +console.log(Object.keys(my_obj)); // console: ['foo'] +</pre> + +<p>如果想取得物件的所有屬性,包括非可列舉的屬性,請參閱 {{jsxref("Object.getOwnPropertyNames()")}}.</p> + +<h2 id="備註">備註</h2> + +<p>在 ES5 中,如果這個方法的參數不是一個標準物件(例如原始型別),將會產生 {{jsxref("TypeError")}}錯誤。而在 ES2015,非物件的參數將會強制轉換成物件。</p> + +<pre class="brush: js">Object.keys("foo"); +// TypeError: "foo" is not an object (ES5 code) + +Object.keys("foo"); +// ["0", "1", "2"] (ES2015 code) +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p>如需在原生不支援、較舊的環境中增加 <code>Object.keys</code> 的相容性,請複製以下片段:</p> + +<pre class="brush: js">// From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys +if (!Object.keys) { + Object.keys = (function() { + 'use strict'; + var hasOwnProperty = Object.prototype.hasOwnProperty, + hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString'), + dontEnums = [ + 'toString', + 'toLocaleString', + 'valueOf', + 'hasOwnProperty', + 'isPrototypeOf', + 'propertyIsEnumerable', + 'constructor' + ], + dontEnumsLength = dontEnums.length; + + return function(obj) { + if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) { + throw new TypeError('Object.keys called on non-object'); + } + + var result = [], prop, i; + + for (prop in obj) { + if (hasOwnProperty.call(obj, prop)) { + result.push(prop); + } + } + + if (hasDontEnumBug) { + for (i = 0; i < dontEnumsLength; i++) { + if (hasOwnProperty.call(obj, dontEnums[i])) { + result.push(dontEnums[i]); + } + } + } + return result; + }; + }()); +} +</pre> + +<p>請注意以上的代碼片段在 IE7 中( IE8 也有可能 ),從不同的 window 傳入物件將包含非可列舉的 key 。</p> + +<p>較精簡的瀏覽器 Polyfill,請參閱 <a href="http://tokenposts.blogspot.com.au/2012/04/javascript-objectkeys-browser.html">Javascript - Object.keys Browser Compatibility</a>.</p> + +<h2 id="規範">規範</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.2.3.14', 'Object.keys')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.8.5.</td> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-object.keys', 'Object.keys')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-object.keys', 'Object.keys')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome("5")}}</td> + <td>{{CompatGeckoDesktop("2.0")}}</td> + <td>{{CompatIE("9")}}</td> + <td>{{CompatOpera("12")}}</td> + <td>{{CompatSafari("5")}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</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>Basic support</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="參見">參見</h2> + +<ul> + <li><a href="/en-US/docs/Enumerability_and_ownership_of_properties">Enumerability and ownership of properties</a></li> + <li>{{jsxref("Object.prototype.propertyIsEnumerable()")}}</li> + <li>{{jsxref("Object.create()")}}</li> + <li>{{jsxref("Object.getOwnPropertyNames()")}}</li> + <li>{{jsxref("Object.values()")}} {{experimental_inline}}</li> + <li>{{jsxref("Object.entries()")}} {{experimental_inline}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/object/preventextensions/index.html b/files/zh-tw/web/javascript/reference/global_objects/object/preventextensions/index.html new file mode 100644 index 0000000000..bc046cf87b --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/object/preventextensions/index.html @@ -0,0 +1,179 @@ +--- +title: Object.preventExtensions() +slug: Web/JavaScript/Reference/Global_Objects/Object/preventExtensions +translation_of: Web/JavaScript/Reference/Global_Objects/Object/preventExtensions +--- +<div>{{JSRef}}</div> + +<p><code><strong>Object.preventExtensions()</strong></code> 用來避免物件被新增新的屬性。</p> + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox"><code>Object.preventExtensions(<var>obj</var>)</code></pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>obj</code></dt> + <dd>要被用作無法擴充的物件。</dd> +</dl> + +<h2 id="描述">描述</h2> + +<p>物件如果可以被增加新的屬性,我們稱它可以被擴充(extensible)。<code>Object.preventExtensions()</code> 標註物件使它無法被擴充,所以在它被標註為無法擴充當下,它將無法再增加新的屬性。不過注意一點,在一般狀況下,被標註為無法擴充的物件,其屬性仍可被刪除(<em>deleted</em>)。嘗試去增加屬性將會導致失敗,可能會沒有結果產生,或是傳回一個 {{jsxref("TypeError")}} (最常見,但並不是一定,當在{{jsxref("Functions_and_function_scope/Strict_mode", "strict mode", "", 1)}})。</p> + +<p><code>Object.preventExtensions() 只有避免物件被增加屬性,屬性仍可以被增加至 </code>object prototype 。不過,呼叫 <code>Object.preventExtensions() 使用在物件上,就可以使其 </code>{{jsxref("Object.proto", "__proto__")}} {{deprecated_inline}} 屬性無法被擴充。</p> + +<p>如果能把可擴充物件,轉成無法擴充物件,在 ECMAScript 5 規範中,它並沒有任何方法轉回來。</p> + +<h2 id="範例">範例</h2> + +<pre class="brush: js">// Object.preventExtensions 傳回一個被無法擴充的物件 +var obj = {}; +var obj2 = Object.preventExtensions(obj); +obj === obj2; // true + +// 預設下,物件可以被擴充 +var empty = {}; +Object.isExtensible(empty); // === true + +// ...但是以下情況之後,無法再被變更。 +Object.preventExtensions(empty); +Object.isExtensible(empty); // === false + +// Object.defineProperty throws 當為無法擴充的物件增加屬性 +var nonExtensible = { removable: true }; +Object.preventExtensions(nonExtensible); +Object.defineProperty(nonExtensible, 'new', { value: 8675309 }); // throws a TypeError + +// 在 strict mode 中,嘗試去新增屬性給無法擴充物件,將 throws 出一個 TypeError。 +function fail() { + 'use strict'; + nonExtensible.newProperty = 'FAIL'; // throws a TypeError +} +fail(); + +// EXTENSION (only works in engines supporting __proto__ +// (which is deprecated. Use Object.getPrototypeOf instead)): +// A non-extensible object's prototype is immutable. +var fixed = Object.preventExtensions({}); +fixed.__proto__ = { oh: 'hai' }; // throws a TypeError +</pre> + +<h2 id="筆記">筆記</h2> + +<p>在ES5中,如果給祝個方法的參數為非物件,它將造成一個 {{jsxref("TypeError")}} 。不過在 ES6 中,非物件參數會被正常處理。另外,如果它原本就是個無法擴充物件,就只是回傳本身。</p> + +<pre class="brush: js">Object.preventExtensions(1); +// TypeError: 1 is not an object (ES5 code) + +Object.preventExtensions(1); +// 1 (ES6 code) +</pre> + +<h2 id="規範">規範</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.2.3.10', 'Object.preventExtensions')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.8.5.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object.preventextensions', 'Object.preventExtensions')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-object.preventextensions', 'Object.preventExtensions')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容度">瀏覽器相容度</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome("6")}}</td> + <td>{{CompatGeckoDesktop("2.0")}}</td> + <td>{{CompatIE("9")}}</td> + <td>{{CompatOpera("12")}}</td> + <td>{{CompatSafari("5.1")}}</td> + </tr> + <tr> + <td>ES6 behavior for non-object argument</td> + <td>{{CompatChrome("44")}}</td> + <td>{{CompatGeckoDesktop("35.0")}}</td> + <td>{{CompatIE("11")}}</td> + <td>{{CompatOpera("31")}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</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>Basic support</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>ES6 behavior for non-object argument</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("35.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="閱讀更多">閱讀更多</h2> + +<ul> + <li>{{jsxref("Object.isExtensible()")}}</li> + <li>{{jsxref("Object.seal()")}}</li> + <li>{{jsxref("Object.isSealed()")}}</li> + <li>{{jsxref("Object.freeze()")}}</li> + <li>{{jsxref("Object.isFrozen()")}}</li> + <li>{{jsxref("Reflect.preventExtensions()")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/object/proto/index.html b/files/zh-tw/web/javascript/reference/global_objects/object/proto/index.html new file mode 100644 index 0000000000..5ba5c8f615 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/object/proto/index.html @@ -0,0 +1,137 @@ +--- +title: Object.prototype.__proto__ +slug: Web/JavaScript/Reference/Global_Objects/Object/proto +translation_of: Web/JavaScript/Reference/Global_Objects/Object/proto +--- +<div class="warning"> +<p><strong>Warning:</strong> 基於現代Javascript引擎最佳化物件屬性存取的方法,改變一個物件的 <code>[[Prototype]]</code> 在任何瀏覽器或是Javascript引擎都是非常慢的操作?。改變繼承屬性對效能的影響微妙且深遠,不僅僅只是影響執行 <code>obj.__proto__ = ...</code> 的時間,而是會影響到所有有存取到被改變 <code>[[Prototype]]</code> 的物件的程式碼的執行時間。如果你在乎效能的話就應該避免改變一個物件的 <code>[[Prototype]]</code> 。反之,請用 {{jsxref("Object.create()")}} 來產生一個擁有 <code>[[Prototype]]</code> 的物件。</p> +</div> + +<div class="warning"> +<p><strong>Warning:</strong> 雖然 <code>Object.prototype.__proto__</code> 在今日已經被絕大部分的瀏覽器所支援,其存在與確切的行為只有在 ECMAScript 2015 規範才被標準化成一個歷史功能來確保相容性。為了更好的支援,建議使用{{jsxref("Object.getPrototypeOf()")}}。</p> +</div> + +<div>{{JSRef}}</div> + +<p>The <code>__proto__</code> property of {{jsxref("Object.prototype")}} is an accessor property (a getter function and a setter function) that exposes the internal <code>[[Prototype]]</code> (either an object or {{jsxref("Global_Objects/null", "null")}}) of the object through which it is accessed.</p> + +<p>The use of <code>__proto__</code> is controversial, and has been discouraged. It was never originally included in the EcmaScript language spec, but modern browsers decided to implement it anyway. Only recently, the <code>__proto__</code> property has been standardized in the ECMAScript 2015 language specification for web browsers to ensure compatibility, so will be supported into the future. It is deprecated in favor of {{jsxref("Object.getPrototypeOf")}}/{{jsxref("Reflect.getPrototypeOf")}} and {{jsxref("Object.setPrototypeOf")}}/{{jsxref("Reflect.setPrototypeOf")}} (though still, setting the <code>[[Prototype]]</code> of an object is a slow operation that should be avoided if performance is a concern).</p> + +<p>The <code>__proto__</code> property can also be used in an object literal definition to set the object <code>[[Prototype]]</code> on creation, as an alternative to {{jsxref("Object.create()")}}. See: <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer">object initializer / literal syntax</a>.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="brush: js">var Circle = function () {}; +var shape = {}; +var circle = new Circle(); + +// Set the object prototype. +// DEPRECATED. This is for example purposes only. DO NOT DO THIS in real code. +shape.__proto__ = circle; + +// Get the object prototype +console.log(shape.__proto__ === circle); // true +</pre> + +<pre class="brush: js">var shape = function () {}; +var p = { + a: function () { + console.log('aaa'); + } +}; +shape.prototype.__proto__ = p; + +var circle = new shape(); +circle.a(); // aaa +console.log(shape.prototype === circle.__proto__); // true + +// or +var shape = function () {}; +var p = { + a: function () { + console.log('a'); + } +}; + +var circle = new shape(); +circle.__proto__ = p; +circle.a(); // a +console.log(shape.prototype === circle.__proto__); // false + +// or +function test() {}; +test.prototype.myname = function () { + console.log('myname'); +}; + +var a = new test(); +console.log(a.__proto__ === test.prototype); // true +a.myname(); // myname + + +// or +var fn = function () {}; +fn.prototype.myname = function () { + console.log('myname'); +}; + +var obj = { + __proto__: fn.prototype +}; + +obj.myname(); // myname +</pre> + +<p>Note: that is two underscores, followed by the five characters "proto", followed by two more underscores.</p> + +<h2 id="Description">Description</h2> + +<p>The <code>__proto__</code> getter function exposes the value of the internal <code>[[Prototype]]</code> of an object. For objects created using an object literal, this value is {{jsxref("Object.prototype")}}. For objects created using array literals, this value is {{jsxref("Array.prototype")}}. For functions, this value is {{jsxref("Function.prototype")}}. For objects created using <code>new fun</code>, where <code>fun</code> is one of the built-in constructor functions provided by JavaScript ({{jsxref("Array")}}, {{jsxref("Boolean")}}, {{jsxref("Date")}}, {{jsxref("Number")}}, {{jsxref("Object")}}, {{jsxref("String")}}, and so on — including new constructors added as JavaScript evolves), this value is always <code>fun.prototype</code>. For objects created using <code>new fun</code>, where <code>fun</code> is a function defined in a script, this value is the value of <code>fun.prototype</code>. (That is, if the constructor didn't return an other object explicitly, or the <code>fun.prototype</code> has been reassigned since the instance was created).</p> + +<p>The <code>__proto__</code> setter allows the <code>[[Prototype]]</code> of an object to be mutated. The object must be extensible according to {{jsxref("Object.isExtensible()")}}: if it is not, a {{jsxref("Global_Objects/TypeError", "TypeError")}} is thrown. The value provided must be an object or {{jsxref("Global_Objects/null", "null")}}. Providing any other value will do nothing.</p> + +<p>To understand how prototypes are used for inheritance, see guide article <a href="/en-US/docs/Web/JavaScript/Guide/Inheritance_and_the_prototype_chain">Inheritance and the prototype chain</a>.</p> + +<p>The <code>__proto__</code> property is a simple accessor property on {{jsxref("Object.prototype")}} consisting of a getter and setter function. A property access for <code>__proto__</code> that eventually consults {{jsxref("Object.prototype")}} will find this property, but an access that does not consult {{jsxref("Object.prototype")}} will not find it. If some other <code>__proto__</code> property is found before {{jsxref("Object.prototype")}} is consulted, that property will hide the one found on {{jsxref("Object.prototype")}}.</p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-additional-properties-of-the-object.prototype-object', 'Object.prototype.__proto__')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Included in the (normative) annex for additional ECMAScript legacy features for Web browsers (note that the specification codifies what is already in implementations).</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-additional-properties-of-the-object.prototype-object', 'Object.prototype.__proto__')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Object.proto")}}</p> +</div> + +<h2 id="Compatibility_notes">Compatibility notes</h2> + +<p>While the ECMAScript 2015 specification dictates that support for <code>__proto__</code> is required <em>only</em> for web browsers (although being normative), other environments may support it as well for legacy usage.</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Object.prototype.isPrototypeOf()")}}</li> + <li>{{jsxref("Object.getPrototypeOf()")}}</li> + <li>{{jsxref("Object.setPrototypeOf()")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/object/prototype/index.html b/files/zh-tw/web/javascript/reference/global_objects/object/prototype/index.html new file mode 100644 index 0000000000..21c2a53985 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/object/prototype/index.html @@ -0,0 +1,218 @@ +--- +title: Object.prototype +slug: Web/JavaScript/Reference/Global_Objects/Object/prototype +tags: + - JavaScript + - Object + - 待翻譯 +translation_of: Web/JavaScript/Reference/Global_Objects/Object +--- +<div>{{JSRef}}</div> + +<p><code><strong>Object.prototype</strong></code> 代表 {{jsxref("Object")}} 的原型物件。</p> + +<div>{{js_property_attributes(0, 0, 0)}}</div> + +<h2 id="描述">描述</h2> + +<p>All objects in JavaScript are descended from {{jsxref("Object")}}; all objects inherit methods and properties from <code>Object.prototype</code>, although they may be overridden (except an <code>Object</code> with a <code>null</code> prototype, i.e. <code>Object.create(null)</code>). For example, other constructors' prototypes override the <code>constructor</code> property and provide their own {{jsxref("Object.prototype.toString()", "toString()")}} methods. Changes to the <code>Object</code> prototype object are propagated to all objects unless the properties and methods subject to those changes are overridden further along the prototype chain.</p> + +<h2 id="屬性">屬性</h2> + +<dl> + <dt>{{jsxref("Object.prototype.constructor")}}</dt> + <dd>Specifies the function that creates an object's prototype.</dd> + <dt>{{jsxref("Object.prototype.__proto__")}} {{non-standard_inline}}</dt> + <dd>Points to the object which was used as prototype when the object was instantiated.</dd> + <dt>{{jsxref("Object.prototype.__noSuchMethod__")}} {{non-standard_inline}}</dt> + <dd>Allows a function to be defined that will be executed when an undefined object member is called as a method.</dd> + <dt><s class="obsoleteElement">{{jsxref("Object.prototype.__count__")}} {{obsolete_inline}}</s></dt> + <dd><s class="obsoleteElement">Used to return the number of enumerable properties directly on a user-defined object, but has been removed.</s></dd> + <dt><s class="obsoleteElement">{{jsxref("Object.prototype.__parent__")}} {{obsolete_inline}}</s></dt> + <dd><s class="obsoleteElement">Used to point to an object's context, but has been removed.</s></dd> +</dl> + +<h2 id="方法">方法</h2> + +<dl> + <dt>{{jsxref("Object.prototype.__defineGetter__()")}} {{non-standard_inline}} {{deprecated_inline}}</dt> + <dd>Associates a function with a property that, when accessed, executes that function and returns its return value.</dd> + <dt>{{jsxref("Object.prototype.__defineSetter__()")}} {{non-standard_inline}} {{deprecated_inline}}</dt> + <dd>Associates a function with a property that, when set, executes that function which modifies the property.</dd> + <dt>{{jsxref("Object.prototype.__lookupGetter__()")}} {{non-standard_inline}} {{deprecated_inline}}</dt> + <dd>Returns the function associated with the specified property by the {{jsxref("Object.defineGetter", "__defineGetter__")}} method.</dd> + <dt>{{jsxref("Object.prototype.__lookupSetter__()")}} {{non-standard_inline}} {{deprecated_inline}}</dt> + <dd>Returns the function associated with the specified property by the {{jsxref("Object.defineSetter", "__defineSetter__")}} method.</dd> + <dt>{{jsxref("Object.prototype.hasOwnProperty()")}}</dt> + <dd>Returns a boolean indicating whether an object contains the specified property as a direct property of that object and not inherited through the prototype chain.</dd> + <dt>{{jsxref("Object.prototype.isPrototypeOf()")}}</dt> + <dd>Returns a boolean indication whether the specified object is in the prototype chain of the object this method is called upon.</dd> + <dt>{{jsxref("Object.prototype.propertyIsEnumerable()")}}</dt> + <dd>Returns a boolean indicating if the internal <a href="/en-US/docs/ECMAScript_DontEnum_attribute" title="ECMAScript_DontEnum_attribute">ECMAScript DontEnum attribute</a> is set.</dd> + <dt>{{jsxref("Object.prototype.toSource()")}} {{non-standard_inline}}</dt> + <dd>Returns string containing the source of an object literal representing the object that this method is called upon; you can use this value to create a new object.</dd> + <dt>{{jsxref("Object.prototype.toLocaleString()")}}</dt> + <dd>Calls {{jsxref("Object.toString", "toString()")}}.</dd> + <dt>{{jsxref("Object.prototype.toString()")}}</dt> + <dd>Returns a string representation of the object.</dd> + <dt>{{jsxref("Object.prototype.unwatch()")}} {{non-standard_inline}}</dt> + <dd>Removes a watchpoint from a property of the object.</dd> + <dt>{{jsxref("Object.prototype.valueOf()")}}</dt> + <dd>Returns the primitive value of the specified object.</dd> + <dt>{{jsxref("Object.prototype.watch()")}} {{non-standard_inline}}</dt> + <dd>Adds a watchpoint to a property of the object.</dd> + <dt><s class="obsoleteElement">{{jsxref("Object.prototype.eval()")}} {{obsolete_inline}}</s></dt> + <dd><s class="obsoleteElement">Used to evaluate a string of JavaScript code in the context of the specified object, but has been removed.</s></dd> +</dl> + +<h2 id="範例">範例</h2> + +<p>因為 JavaScript 並沒有子類別的物件,所以原型是個很有用的解決辦法, 使某些函數作為物件的基本類別物件。例如:</p> + +<pre class="brush: js">var Person = function() { + this.canTalk = true; +}; + +Person.prototype.greet = function() { + if (this.canTalk) { + console.log('Hi, I am ' + this.name); + } +}; + +var Employee = function(name, title) { + Person.call(this); + this.name = name; + this.title = title; +}; + +Employee.prototype = Object.create(Person.prototype); +Employee.prototype.constructor = Employee; + +Employee.prototype.greet = function() { + if (this.canTalk) { + console.log('Hi, I am ' + this.name + ', the ' + this.title); + } +}; + +var Customer = function(name) { + Person.call(this); + this.name = name; +}; + +Customer.prototype = Object.create(Person.prototype); +Customer.prototype.constructor = Customer; + +var Mime = function(name) { + Person.call(this); + this.name = name; + this.canTalk = false; +}; + +Mime.prototype = Object.create(Person.prototype); +Mime.prototype.constructor = Mime; + +var bob = new Employee('Bob', 'Builder'); +var joe = new Customer('Joe'); +var rg = new Employee('Red Green', 'Handyman'); +var mike = new Customer('Mike'); +var mime = new Mime('Mime'); + +bob.greet(); +// Hi, I am Bob, the Builder + +joe.greet(); +// Hi, I am Joe + +rg.greet(); +// Hi, I am Red Green, the Handyman + +mike.greet(); +// Hi, I am Mike + +mime.greet(); +</pre> + +<h2 id="規範">規範</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.2.3.1', 'Object.prototype')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object.prototype', 'Object.prototype')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</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>Feature</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>Basic support</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><a href="/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript">Introduction to Object-Oriented JavaScript</a></li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/object/watch/index.html b/files/zh-tw/web/javascript/reference/global_objects/object/watch/index.html new file mode 100644 index 0000000000..9dc8afa27f --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/object/watch/index.html @@ -0,0 +1,191 @@ +--- +title: Object.prototype.watch() +slug: Web/JavaScript/Reference/Global_Objects/Object/watch +translation_of: Archive/Web/JavaScript/Object.watch +--- +<div>{{JSRef}}</div> + +<div class="warning"> +<p><strong>Warning:</strong> Generally you should avoid using <code>watch()</code> and {{jsxref("Object.prototype.unwatch", "unwatch()")}} when possible. These two methods are implemented only in Gecko, and they're intended primarily for debugging use. In addition, using watchpoints has a serious negative impact on performance, which is especially true when used on global objects, such as <code>window</code>. You can usually use <a href="/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Defining_getters_and_setters">setters and getters</a> or proxies instead. See {{anch("Browser compatibility")}} for details. Also, do not confuse {{jsxref("Object.prototype.watch", "Object.watch")}} with {{jsxref("Object.prototype.observe", "Object.observe")}}.</p> +</div> + +<p>The <code><strong>watch()</strong></code> method watches for a property to be assigned a value and runs a function when that occurs.</p> + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox"><code><var>obj</var>.watch(<var>prop</var>, <var>handler</var>)</code></pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>prop</code></dt> + <dd>所需要監聽其值是否改變的物件屬性</dd> + <dt><code>handler</code></dt> + <dd>當監聽的變數其數值變換時所執行的function</dd> +</dl> + +<h3 id="回傳值">回傳值</h3> + +<p>{{jsxref("undefined")}}.</p> + +<h2 id="Description">Description</h2> + +<p>Watches for assignment to a property named <code>prop</code> in this object, 呼叫 <code>handler(prop, oldval, newval)</code> whenever <code>prop</code> is set and storing the return value in that property. A watchpoint can filter (or nullify) the value assignment, by returning a modified <code>newval</code> (or by returning <code>oldval</code>).</p> + +<p>當你刪掉所監聽的物件屬性,並不會結束針對該物件屬性的監聽。當你重新產生該屬性時,監聽依舊維持作用。</p> + +<p>要停止該次監聽, 須使用 {{jsxref("Object.unwatch", "unwatch()")}} 函式. By default, the <code>watch</code> method is inherited by every object descended from {{jsxref("Object")}}.</p> + +<p>The JavaScript debugger has functionality similar to that provided by this method, as well as other debugging options. For information on the debugger, see <a href="/en-US/docs/Venkman">Venkman</a>.</p> + +<p>In Firefox, <code>handler</code> is only called from assignments in script, not from native code. For example, <code>window.watch('location', myHandler)</code> will not call <code>myHandler</code> if the user clicks a link to an anchor within the current document. However, <code>window.location += '#myAnchor'</code> will call <code>myHandler</code>.</p> + +<div class="note"> +<p><strong>Note:</strong> Calling <code>watch()</code> on an object for a specific property overrides any previous handler attached for that property.</p> +</div> + +<h2 id="範例">範例</h2> + +<h3 id="使用watch_和_unwatch">使用watch 和 unwatch</h3> + +<pre class="brush: js">var o = { p: 1 }; + +o.watch('p', function (id, oldval, newval) { + console.log('o.' + id + ' changed from ' + oldval + ' to ' + newval); + return newval; +}); + +o.p = 2; +o.p = 3; +delete o.p; +o.p = 4; + +o.unwatch('p'); +o.p = 5; +</pre> + +<p>上述程式執行結果:</p> + +<pre>o.p changed from 1 to 2 +o.p changed from 2 to 3 +o.p changed from undefined to 4 +</pre> + +<h3 id="使用_watch_驗證物件的屬性">使用 <code>watch</code> 驗證物件的屬性</h3> + +<p>You can use <code>watch</code> to test any assignment to an object's properties. This example ensures that every Person always has a valid name and an age between 0 and 200.</p> + +<pre class="brush: js">Person = function(name, age) { + this.watch('age', Person.prototype._isValidAssignment); + this.watch('name', Person.prototype._isValidAssignment); + this.name = name; + this.age = age; +}; + +Person.prototype.toString = function() { + return this.name + ', ' + this.age; +}; + +Person.prototype._isValidAssignment = function(id, oldval, newval) { + if (id === 'name' && (!newval || newval.length > 30)) { + throw new RangeError('invalid name for ' + this); + } + if (id === 'age' && (newval < 0 || newval > 200)) { + throw new RangeError('invalid age for ' + this); + } + return newval; +} + +will = new Person('Will', 29); +console.log(will); // Will, 29 + +try { + will.name = ''; +} catch (e) { + console.log(e); +} + +try { + will.age = -4; +} catch (e) { + console.log(e); +} +</pre> + +<p>上述程式執行結果:</p> + +<pre>Will, 29 +RangeError: invalid name for Will, 29 +RangeError: invalid age for Will, 29 +</pre> + +<h2 id="規格">規格</h2> + +<p>Not part of any specifications. Implemented in JavaScript 1.2.</p> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</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>Basic support</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Compatibility_notes">Compatibility notes</h2> + +<ul> + <li>This <a class="external link-https" href="https://gist.github.com/384583">Polyfill</a> offers <code>watch</code> to all ES5 compatible browsers.</li> + <li>Using a {{jsxref("Proxy")}} enables you do even deeper changes to how property assignments work.</li> + <li>Calling <code>watch()</code> on the {{domxref("Document")}} object throws a {{jsxref("TypeError")}} since Firefox 23 ({{bug(903332)}}). This regression has been fixed with Firefox 27.</li> +</ul> + +<h2 id="參閱">參閱</h2> + +<ul> + <li>{{jsxref("Object.unwatch()")}}</li> + <li>{{jsxref("Object.observe()")}} {{obsolete_inline}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/parseint/index.html b/files/zh-tw/web/javascript/reference/global_objects/parseint/index.html new file mode 100644 index 0000000000..ee365f3ce3 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/parseint/index.html @@ -0,0 +1,193 @@ +--- +title: parseInt() +slug: Web/JavaScript/Reference/Global_Objects/parseInt +tags: + - Global method + - parseInt + - 整數 + - 進位制 +translation_of: Web/JavaScript/Reference/Global_Objects/parseInt +--- +<div>{{jsSidebar("Objects")}}</div> + +<p><code><strong>parseInt()</strong></code> 函式能將輸入的字串轉成整數。</p> + +<div>{{EmbedInteractiveExample("pages/js/globalprops-parseint.html")}}</div> + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox">parseInt(<em>string</em>, <em>radix</em>);</pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>string</code></dt> + <dd>待轉成數字的字串。若 <code>string</code> 參數類型不是字串的話,會先將其轉成字串(相當於先執行 <code><a href="http://www.ecma-international.org/ecma-262/6.0/#sec-tostring">ToString</a></code> 再執行 <code>parseInt</code>)空白值會被忽略。</dd> + <dt><code>radix</code></dt> + <dd>從 2 到 36,能代表該進位系統的數字。例如說指定 <code>10</code> 就等於指定十進位。<strong>一定要定義這個參數</strong>以避免他人的困惑、也好預估函式的行為。如果沒有指定 radix 的話,給出的結果會按照實做不同而異,請注意,通常預設值<strong>不是</strong> 10 進位。</dd> +</dl> + +<h3 id="回傳值">回傳值</h3> + +<p>藉由給定字串作轉換後的數字。若第一個字符無法轉換為數字,則回傳 {{jsxref("NaN")}}。</p> + +<h2 id="說明">說明</h2> + +<p><code>parseInt</code> 函式會把第一個參數變成字串、解析它、再回傳整數或是 <code>NaN</code>。如果不是 <code>NaN</code>,回傳值會把第一個參數,參照指定的 <var>radix</var> 後,以十進位表示。例如,<var>radix</var> 指定為 10 的話,它會以十進位為單位轉換、8 是八進位、16 是十六進位,依此類推。For radices above <code>10</code>, the letters of the alphabet indicate numerals greater than <code>9</code>. For example, for hexadecimal numbers (base 16), <code>A</code> through <code>F</code> are used.</p> + +<p>如果說 <code>parseInt</code> 碰上了無法被 radix 指定的進位制所轉換的字元,它會忽略該字元、以及其後所有字元,並只回傳至該位置為止的解析數值結果。<code>parseInt</code> 將數字擷取、轉換成整數數值。 可以接受字串首尾出現空白。</p> + +<p>Because some numbers include the <code>e</code> character in their string representation (e.g. <strong><code>6.022e23</code></strong>), using <code>parseInt</code> to truncate numeric values will produce unexpected results when used on very large or very small numbers. <code>parseInt</code> should not be used as a substitute for {{jsxref("Math.floor()")}}.</p> + +<p>如果 <var>radix</var> 是 <code>undefined</code> 或 0(或留空)的話,JavaScript 會:</p> + +<ul> + <li>如果 <code>string</code> 由 "0x" 或 "0X" 開始,<var>radix</var> 會變成代表十六進位的 16,並解析字串的餘數。</li> + <li>如果 <code>string</code> 由 0 開始,則 <var>radix</var> 會變成代表八進位的 8 或十進位的 10,但到底會變成 8 還是 10 則取決於各實做。ECMAScript 規定用代表十進位的 10,但也不是所有瀏覽器都支持。因此,<strong>使用 <code>parseInt</code> 時一定要指定 radix</strong>。</li> + <li>如果 <code>string</code> 由其他字串開始,radix 就會是十進位的 10。</li> +</ul> + +<p>如果第一個字串無法被解析為任何數字,<code>parseInt</code> 會回傳 <code>NaN</code>。</p> + +<p>For arithmetic purposes, the <code>NaN</code> value is not a number in any radix. You can call the {{jsxref("isNaN")}} function to determine if the result of <code>parseInt</code> is <code>NaN</code>. If <code>NaN</code> is passed on to arithmetic operations, the operation results will also be <code>NaN</code>.</p> + +<p>若想將數字轉成特定的進位制,可使用 <code>intValue.toString(radix)</code>。</p> + +<h2 id="範例">範例</h2> + +<h3 id="使用_parseInt">使用 <code>parseInt</code></h3> + +<p>以下的範例,回傳的值均為 <strong><code>15</code></strong>:</p> + +<pre class="brush: js">parseInt(" 0xF", 16); +parseInt(" F", 16); +parseInt("17", 8); +parseInt(021, 8); +parseInt("015", 10); // parseInt(015, 10); will return 15 +parseInt(15.99, 10); +parseInt("15,123", 10); +parseInt("FXX123", 16); +parseInt("1111", 2); +parseInt("15*3", 10); +parseInt("15e2", 10); +parseInt("15px", 10); +parseInt("12", 13); +</pre> + +<p>以下均回傳 <strong><code>NaN</code></strong>:</p> + +<pre class="brush: js">parseInt("Hello", 8); // 根本不是數字 +parseInt("546", 2); // 在二進位無效 +</pre> + +<p>以下的範例,回傳的值均為 <strong><code>-15</code></strong>:</p> + +<pre class="brush: js">parseInt("-F", 16); +parseInt("-0F", 16); +parseInt("-0XF", 16); +parseInt(-15.1, 10) +parseInt(" -17", 8); +parseInt(" -15", 10); +parseInt("-1111", 2); +parseInt("-15e1", 10); +parseInt("-12", 13); +</pre> + +<p>下例會回傳 <strong><code>4</code></strong>:</p> + +<pre class="brush: js">parseInt(4.7, 10); +parseInt(4.7 * 1e22, 10); // Very large number becomes 4 +parseInt(0.00000000000434, 10); // Very small number becomes 4 +</pre> + +<p>下例會回傳 <strong><code>224</code></strong>:</p> + +<pre class="brush: js">parseInt("0e0", 16); +</pre> + +<h2 id="無_radix_情況下的八進制">無 radix 情況下的八進制</h2> + +<p>雖說已在 ECMAScript 3 提議並於 ECMAScript 5 禁用,但部分 javascript 編譯器仍會在特殊情況下,將 str 視作八進位數字(當數字以 <code>0</code> 開頭時)。以下為可能發生這種問題的情況:(<strong>永遠要宣告 radix 以避開這不可靠的行為</strong>)</p> + +<pre class="brush: js">parseInt("0e0"); // 0 +parseInt("08"); // 0, '8' is not an octal digit. +</pre> + +<h3 id="ECMAScript_5_移除八進位轉譯(octal_interpretation)">ECMAScript 5 移除八進位轉譯(octal interpretation)</h3> + +<p>The ECMAScript 5 specification of the function <code>parseInt</code> no longer allows implementations to treat Strings beginning with a <code>0</code> character as octal values. ECMAScript 5 states:</p> + +<p>The <code>parseInt</code> function produces an integer value dictated by interpretation of the contents of the string argument according to the specified radix. Leading white space in string is ignored. If radix is undefined or <code>0</code>, it is assumed to be <code>10</code> except when the number begins with the character pairs <code>0x</code> or <code>0X</code>, in which case a radix of 16 is assumed.</p> + +<p>This differs from ECMAScript 3, which discouraged but allowed octal interpretation.</p> + +<p>Many implementations have not adopted this behavior as of 2013, and because older browsers must be supported, <strong>always specify a radix</strong>.</p> + +<h2 id="嚴謹的解析_function">嚴謹的解析 function</h2> + +<p>有的時候,使用更嚴謹的 code 能夠更精確地轉換整數值。 Regular expressions 可以幫你:</p> + +<pre class="brush: js">filterInt = function (value) { + if(/^(\-|\+)?([0-9]+|Infinity)$/.test(value)) + return Number(value); + return NaN; +} + +console.log(filterInt('421')); // 421 +console.log(filterInt('-421')); // -421 +console.log(filterInt('+421')); // 421 +console.log(filterInt('Infinity')); // Infinity +console.log(filterInt('421e+0')); // NaN +console.log(filterInt('421hop')); // NaN +console.log(filterInt('hop1.61803398875')); // NaN +console.log(filterInt('1.61803398875')); // NaN +</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('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>初始定義</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.1.2.2', 'parseInt')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-parseint-string-radix', 'parseInt')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-parseint-string-radix', 'parseInt')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + + + +<p>{{Compat("javascript.builtins.parseInt")}}</p> + +<h2 id="延伸閱讀">延伸閱讀</h2> + +<ul> + <li>{{jsxref("Global_Objects/parseFloat", "parseFloat()")}}</li> + <li>{{jsxref("Number.parseFloat()")}}</li> + <li>{{jsxref("Number.parseInt()")}}</li> + <li>{{jsxref("Global_Objects/isNaN", "isNaN()")}}</li> + <li>{{jsxref("Number.toString()")}}</li> + <li>{{jsxref("Object.valueOf")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/promise/all/index.html b/files/zh-tw/web/javascript/reference/global_objects/promise/all/index.html new file mode 100644 index 0000000000..eb18ce63f9 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/promise/all/index.html @@ -0,0 +1,207 @@ +--- +title: Promise.all() +slug: Web/JavaScript/Reference/Global_Objects/Promise/all +translation_of: Web/JavaScript/Reference/Global_Objects/Promise/all +--- +<div>{{JSRef}}</div> + +<p><code><strong>Promise.all()</strong></code> 方法回傳一個 {{jsxref("Promise")}} 物件,當引數 <code>iterable</code> 中所有的 promises 都被實現(resolved),或引數 iterable 不含任何 promise 時,被實現。或以第一個被拒絕的 promise 的原因被拒絕。</p> + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox"><var>Promise.all(iterable)</var>;</pre> + +<dl> + <dt>iterable</dt> + <dd>一個 <a href="https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol">iterable</a> 物件像是 {{jsxref("Array")}} 或 {{jsxref("String")}}。</dd> +</dl> + +<h3 id="回傳值">回傳值</h3> + +<ul> + <li>一個<strong>已被實現(already resolved)</strong>的 {{jsxref("Promise")}},若傳入的 iterable 為空。</li> + <li>一個<strong>非同步地被實現(asynchronously resolved)</strong>的 {{jsxref("Promise")}} 若傳入的 iterable 不含 promise。注意,Google Chrome 58 對此情形回傳一個<strong>已被解決</strong>的 promise。</li> + <li>一個<strong>擱置(pending)</strong>的 {{jsxref("Promise")}},對所有剩餘情形。此 promise 接著被<strong>非同步地</strong>被 resolved/rejected(只要堆疊為空)當 iterable 中所有的 promises 都被實現,或其中一個被拒絕。參見下方關於"Promise.all 的非同步與同步性質"的例子。</li> +</ul> + +<h2 id="描述">描述</h2> + +<p>此方法在聚集(aggregating)多個 promises 的結果時很有幫助。</p> + +<p>實現(Fulfillment):<br> + 若傳入空的 iterable,此方法(同步地)回傳一個已被解決的 promise。若所有傳入的 promises 都被實現,或都不是 promise,<code>Promise.all</code> 回傳的 promise 被非同步地實現。無論是哪個情形,回傳一個以 iterable 其內<strong>所有</strong>值(包含非 promise 值)作為引數的陣列被實現。<br> + </p> + +<p>拒絕(Rejection):<br> + 若任一個傳入的 promise 被拒絕,Promise.all 非同步地以其值被拒絕,無論其他 promises 是否被解決。</p> + +<h2 id="範例">範例</h2> + +<h3 id="使用_Promise.all">使用 <code>Promise.all</code></h3> + +<p><code>Promise.all</code> 等到全部實現(或一個拒絕)。</p> + +<pre class="brush: js">var p1 = Promise.resolve(3); +var p2 = 1337; +var p3 = new Promise((resolve, reject) => { + setTimeout(resolve, 100, 'foo'); +}); + +Promise.all([p1, p2, p3]).then(values => { + console.log(values); // [3, 1337, "foo"] +});</pre> + +<p>若 iterable 含非 promise 值,它們將被忽略,但依然會被記入回傳 promise 陣列值(若被實現):</p> + +<pre class="brush: js">// this will be counted as if the iterable passed is empty, so it gets fulfilled +var p = Promise.all([1,2,3]); +// this will be counted as if the iterable passed contains only the resolved promise with value "444", so it gets fulfilled +var p2 = Promise.all([1,2,3, Promise.resolve(444)]); +// this will be counted as if the iterable passed contains only the rejected promise with value "555", so it gets rejected +var p3 = Promise.all([1,2,3, Promise.reject(555)]); + +// using setTimeout we can execute code after the stack is empty +setTimeout(function(){ + console.log(p); + console.log(p2); + console.log(p3); +}); + +// logs +// Promise { <state>: "fulfilled", <value>: Array[3] } +// Promise { <state>: "fulfilled", <value>: Array[4] } +// Promise { <state>: "rejected", <reason>: 555 }</pre> + +<h3 id="Promise.all_的非同步與同步性質"><code>Promise.all</code> 的非同步與同步性質</h3> + +<p>以下例子驗證了 <code>Promise.all</code> 的非同步性質(asynchronicity)(或同步性質(synchronicity),若傳入的 iterable 是空的):</p> + +<pre class="brush: js">// we are passing as argument an array of promises that are already resolved, +// to trigger Promise.all as soon as possible +var resolvedPromisesArray = [Promise.resolve(33), Promise.resolve(44)]; + +var p = Promise.all(resolvedPromisesArray); +// immediately logging the value of p +console.log(p); + +// using setTimeout we can execute code after the stack is empty +setTimeout(function(){ + console.log('the stack is now empty'); + console.log(p); +}); + +// logs, in order: +// Promise { <state>: "pending" } +// the stack is now empty +// Promise { <state>: "fulfilled", <value>: Array[2] } +</pre> + +<p><code>當</code> <code>Promise.all</code> 被拒絕時發生一樣的事情:</p> + +<pre class="brush: js">var mixedPromisesArray = [Promise.resolve(33), Promise.reject(44)]; +var p = Promise.all(mixedPromisesArray); +console.log(p); +setTimeout(function(){ + console.log('the stack is now empty'); + console.log(p); +}); + +// logs +// Promise { <state>: "pending" } +// the stack is now empty +// Promise { <state>: "rejected", <reason>: 44 } +</pre> + +<p>注意!<code>Promise.all</code> 同步地被解決<strong>若且唯若</strong>傳入的 iterable 為空:</p> + +<pre class="brush: js">var p = Promise.all([]); // will be immediately resolved +var p2 = Promise.all([1337, "hi"]); // non-promise values will be ignored, but the evaluation will be done asynchronously +console.log(p); +console.log(p2) +setTimeout(function(){ + console.log('the stack is now empty'); + console.log(p2); +}); + +// logs +// Promise { <state>: "fulfilled", <value>: Array[0] } +// Promise { <state>: "pending" } +// the stack is now empty +// Promise { <state>: "fulfilled", <value>: Array[2] } +</pre> + +<h3 id="Promise.all_的失敗優先(fail-fast)行為"><code>Promise.all</code> 的失敗優先(fail-fast)行為</h3> + +<p><code>當任一個陣列成員被拒絕則</code> <code>Promise.all</code> 被拒絕。例如,若傳入四個將在一段時間後被解決的 promises,而其中一個立刻被拒絕,則 <code>Promise.all</code> 將立刻被拒絕。</p> + +<pre class="brush: js">var p1 = new Promise((resolve, reject) => { + setTimeout(resolve, 1000, 'one'); +}); +var p2 = new Promise((resolve, reject) => { + setTimeout(resolve, 2000, 'two'); +}); +var p3 = new Promise((resolve, reject) => { + setTimeout(resolve, 3000, 'three'); +}); +var p4 = new Promise((resolve, reject) => { + setTimeout(resolve, 4000, 'four'); +}); +var p5 = new Promise((resolve, reject) => { + reject('reject'); +}); + +Promise.all([p1, p2, p3, p4, p5]).then(values => { + console.log(values); +}, reason => { + console.log(reason) +}); + +//From console: +//"reject" + +//You can also use .catch +Promise.all([p1, p2, p3, p4, p5]).then(values => { + console.log(values); +}).catch(reason => { + console.log(reason) +}); + +//From console: +//"reject" + +</pre> + +<h2 id="規範">規範</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-promise.all', 'Promise.all')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition in an ECMA standard.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-promise.all', 'Promise.all')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<p class="hidden">To contribute to this compatibility data, please write a pull request against this repository: <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a>.</p> + +<p>{{Compat("javascript.builtins.Promise.all")}}</p> + +<h2 id="參見">參見</h2> + +<ul> + <li>{{jsxref("Promise")}}</li> + <li>{{jsxref("Promise.race()")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/promise/catch/index.html b/files/zh-tw/web/javascript/reference/global_objects/promise/catch/index.html new file mode 100644 index 0000000000..d06036c11e --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/promise/catch/index.html @@ -0,0 +1,189 @@ +--- +title: Promise.prototype.catch() +slug: Web/JavaScript/Reference/Global_Objects/Promise/catch +tags: + - EMCAScript 2015 + - JavaScript + - Method + - Promise + - Prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Promise/catch +--- +<div>{{JSRef}}</div> + +<p><strong>catch()</strong> 方法只處理 Promise 的被拒絕狀態,並回傳一個新的 <code>Promise</code> 物件。此方法的行為等同於呼叫 {{jsxref("Promise.then", "Promise.prototype.then(undefined, onRejected)")}}。</p> + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox"><var>p.catch(onRejected)</var>; + +p.catch(function(reason) { + // rejection +}); +</pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt>onRejected</dt> + <dd>一個 {{jsxref("Function")}} ,在 <code>Promise</code> 被拒絕時被呼叫。這個函式有一個引數: + <dl> + <dt><code>reason</code></dt> + <dd>失敗訊息。</dd> + </dl> + 若 onRejected 拋出一個錯誤或回傳一個被拒絕的 Promise,則 catch() 回傳的 Promise 被拒絕;其他情形都是被實現。</dd> +</dl> + +<h3 id="回傳值">回傳值</h3> + +<p>呼叫(<code>catch</code> 的 promise)物件,內部呼叫 <code>Promise.prototype.then</code>,傳入引數 undefined 及 onRejected;接著以之結果回傳(結果為 {{jsxref("Promise")}})。</p> + +<p><strong>內部呼叫演示:</strong></p> + +<pre class="brush: js">// overriding original Promise.prototype.then/catch just to add some logs +(function(Promise){ + var originalThen = Promise.prototype.then; + var originalCatch = Promise.prototype.catch; + + Promise.prototype.then = function(){ + console.log('> > > > > > called .then on %o with arguments: %o', this, arguments); + return originalThen.apply(this, arguments); + }; + Promise.prototype.catch = function(){ + console.log('> > > > > > called .catch on %o with arguments: %o', this, arguments); + return originalCatch.apply(this, arguments); + }; + +})(this.Promise); + + + +// calling catch on an already resolved promise +Promise.resolve().catch(function XXX(){}); + +// logs: +// > > > > > > called .catch on Promise{} with arguments: Arguments{1} [0: function XXX()] +// > > > > > > called .then on Promise{} with arguments: Arguments{2} [0: undefined, 1: function XXX()] +</pre> + +<h2 id="描述">描述</h2> + +<p><code>catch</code> 方法在處理 promise 組合的錯誤時很有幫助。</p> + +<h2 id="範例">範例</h2> + +<h3 id="使用及串接_catch_方法">使用及串接 <code>catch</code> 方法</h3> + +<pre class="brush: js">var p1 = new Promise(function(resolve, reject) { + resolve('Success'); +}); + +p1.then(function(value) { + console.log(value); // "Success!" + throw 'oh, no!'; +}).catch(function(e) { + console.log(e); // "oh, no!" +}).then(function(){ + console.log('after a catch the chain is restored'); +}, function () { + console.log('Not fired due to the catch'); +}); + +// The following behaves the same as above +p1.then(function(value) { + console.log(value); // "Success!" + return Promise.reject('oh, no!'); +}).catch(function(e) { + console.log(e); // "oh, no!" +}).then(function(){ + console.log('after a catch the chain is restored'); +}, function () { + console.log('Not fired due to the catch'); +}); +</pre> + +<h3 id="拋出例外時的陷阱">拋出例外時的陷阱</h3> + +<pre class="brush: js">// Throwing an error will call the catch method most of the time +var p1 = new Promise(function(resolve, reject) { + throw 'Uh-oh!'; +}); + +p1.catch(function(e) { + console.log(e); // "Uh-oh!" +}); + +// Errors thrown inside asynchronous functions will act like uncaught errors +var p2 = new Promise(function(resolve, reject) { + setTimeout(function() { + throw 'Uncaught Exception!'; + }, 1000); +}); + +p2.catch(function(e) { + console.log(e); // This is never called +}); + +// Errors thrown after resolve is called will be silenced +var p3 = new Promise(function(resolve, reject) { + resolve(); + throw 'Silenced Exception!'; +}); + +p3.catch(function(e) { + console.log(e); // This is never called +});</pre> + +<h3 id="如果_Promise_被實現">如果 Promise 被實現</h3> + +<pre class="brush: js">//Create a promise which would not call onReject +var p1 = Promise.resolve("calling next"); + +var p2 = p1.catch(function (reason) { + //This is never called + console.log("catch p1!"); + console.log(reason); +}); + +p2.then(function (value) { + console.log("next promise's onFulfilled"); /* next promise's onFulfilled */ + console.log(value); /* calling next */ +}, function (reason) { + console.log("next promise's onRejected"); + console.log(reason); +});</pre> + +<h2 id="規範">規範</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-promise.prototype.catch', 'Promise.prototype.catch')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition in an ECMA standard.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-promise.prototype.catch', 'Promise.prototype.catch')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<p class="hidden">To contribute to this compatibility data, please write a pull request against this repository: <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a>.</p> + +<p>{{Compat("javascript.builtins.Promise.catch")}}</p> + +<h2 id="參見">參見</h2> + +<ul> + <li>{{jsxref("Promise")}}</li> + <li>{{jsxref("Promise.prototype.then()")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/promise/finally/index.html b/files/zh-tw/web/javascript/reference/global_objects/promise/finally/index.html new file mode 100644 index 0000000000..eef15faf9a --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/promise/finally/index.html @@ -0,0 +1,102 @@ +--- +title: Promise.prototype.finally() +slug: Web/JavaScript/Reference/Global_Objects/Promise/finally +translation_of: Web/JavaScript/Reference/Global_Objects/Promise/finally +--- +<div>{{JSRef}}</div> + +<p><code><strong>finally()</strong></code> 方法會回傳一個 {{jsxref("Promise")}}。當 promise 被 settled 後,無論其結果是 fulfilled 還是 rejected ,都會執行指定的回呼函數。它提供了一個讓 <code>Promise</code> 在被確認後,無論是 fulfilled 或是 rejected 都會執行某些程式碼的一種手段。</p> + +<p>這樣可以避免你在 promise 的 {{jsxref("Promise.then", "then()")}} 和 {{jsxref("Promise.catch", "catch()")}} 重複處理相同的程式碼。</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><var>p.finally(onFinally)</var>; + +p.finally(function() { + // settled(fulfilled 或 rejected) +}); +</pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>onFinally</code></dt> + <dd>當 <code>Promise</code> settled 後呼叫的 {{jsxref("Function")}}。</dd> +</dl> + +<h3 id="Return_value">Return value</h3> + +<p>回傳 {{jsxref("Promise")}} 當 <code>finally</code> 的處理函數 <code>onFinally</code> 被指定時。</p> + +<h2 id="Description">Description</h2> + +<p>當你希望在 promise settled 後且不關心它的結果為何時,執行一些處理或清理的工作, <code>finally()</code> 方法會很有幫助。</p> + +<p><code>finally()</code> 方法非常類似於 <code>.then(onFinally, onFinally)</code> 的呼叫方式,但仍有一些差異:</p> + +<ul> + <li><font><font>當建立行內的函數時,可以只傳遞一次,從而避免重複宣告或為它宣告變數。</font></font></li> + <li><code>finally</code> 的回呼函數並不會接收到任何引數,因其沒有可靠的方式來確認 promise 是被 fulfilled 還是 rejected 。它的使用情境僅適用於當你<em>不關心</em> rejection 的原因或 fulfillment 的值,因此無須提供。範例: + <ul> + <li><font><font>與 </font></font><code>Promise.resolve(2).then(() => {}, () => {})</code><font><font>(將被 resolved 為</font></font><code>undefined</code><font><font>)不同,</font></font><code>Promise.resolve(2).finally(() => {})</code><font><font> 將被 resolved 為</font></font><code>2</code><font><font>。</font></font></li> + <li><font><font>同樣的,與 </font></font><code>Promise.reject(3).then(() => {}, () => {})</code><font><font>(將 fulfilled 為</font></font><code>undefined</code><font><font>)不同,</font></font><code>Promise.reject(3).finally(() => {})</code><font><font> 將被 rejected 為</font></font><code>3</code><font><font>。</font></font></li> + </ul> + </li> +</ul> + +<div class="note"> +<p><strong>備註: </strong>在 finally 回呼中使用 throw (或回傳 rejected promise)會導致新的 promise 被 reject , reject 的原因則是呼叫 throw() 時所指定的值。</p> +</div> + +<h2 id="Examples">Examples</h2> + +<pre class="brush: js">let isLoading = true; + +fetch(myRequest).then(function(response) { + var contentType = response.headers.get("content-type"); + if(contentType && contentType.includes("application/json")) { + return response.json(); + } + throw new TypeError("Oops, we haven't got JSON!"); + }) + .then(function(json) { /* process your JSON further */ }) + .catch(function(error) { console.log(error); }) + .finally(function() { isLoading = false; }); + +</pre> + +<div class="hidden"> +<p>Please do not add polyfills on MDN pages. For more details, refer to: <a href="https://discourse.mozilla.org/t/mdn-rfc-001-mdn-wiki-pages-shouldnt-be-a-distributor-of-polyfills/24500">https://discourse.mozilla.org/t/mdn-rfc-001-mdn-wiki-pages-shouldnt-be-a-distributor-of-polyfills/24500</a></p> +</div> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-promise.prototype.finally', 'Promise.prototype.finally')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p class="hidden">To contribute to this compatibility data, please write a pull request against this repository: <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a>.</p> + +<p>{{Compat("javascript.builtins.Promise.finally")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Promise")}}</li> + <li>{{jsxref("Promise.prototype.then()")}}</li> + <li>{{jsxref("Promise.prototype.catch()")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/promise/index.html b/files/zh-tw/web/javascript/reference/global_objects/promise/index.html new file mode 100644 index 0000000000..8ec1456ae1 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/promise/index.html @@ -0,0 +1,256 @@ +--- +title: Promise +slug: Web/JavaScript/Reference/Global_Objects/Promise +translation_of: Web/JavaScript/Reference/Global_Objects/Promise +--- +<div>{{JSRef}}</div> + +<p><strong><code>Promise</code></strong> 物件代表一個即將完成、或失敗的非同步操作,以及它所產生的值。</p> + +<div class="note"> +<p>此條目為介紹 Promise 建構式。要瞭解 Promise 相關使用方式,請先參考<a href="/zh-TW/docs/Web/JavaScript/Guide/Using_promises">使用 Promise</a>。Promise 建構式主要用於包裹尚未支援 Promise 的函式。</p> +</div> + +<div>{{EmbedInteractiveExample("pages/js/promise-constructor.html")}}</div> + + + +<p class="hidden">The source for this interactive demo is stored in a GitHub repository. If you'd like to contribute to the interactive demo project, please clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> and send us a pull request.</p> + +<h2 id="語法">語法</h2> + +<pre class="brush: js">new Promise( /* executor */ function(resolve, reject) { ... } );</pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt>executor</dt> + <dd>為一個依序接收兩個參數的函式:<code>resolve</code> 及 <code>reject</code>(實現及拒絕回呼函式)。在 Promise 實作中,<code>executor</code> 函式在傳入參數 <code>resolve</code> 與 <code>reject</code> 後會立刻執行(<code>executor</code> 函式會在 <code>Promise</code> 建構式回傳 Promise 物件前被執行)。<code>resolve</code> 與 <code>reject</code> 函式,會在被個別呼叫時,個別執行之。通常 executor 函式會發起一些非同步操作。接著,成功完成後執行 <code>resolve</code> 以完成 promise;或如果有錯誤,執行 <code>rejects</code>。<br>如果 executor 函式在執行中拋出錯誤,promise 會被拒絕(rejected),回傳值也將被忽略。</dd> +</dl> + +<h2 id="描述">描述</h2> + +<p><code><strong>Promise</strong></code> 會代理一個建立時,不用預先得知的值。它使你能夠繫結(associate)著發動非同步操作後,最終的成功值(success value)或失敗訊息(failure reason)的處理函式(handlers)。這讓非同步方法回傳值的方式很像同步方法,但不是回傳最終結果:非同步方法回傳一個 <em>promise</em> 物件作為未來某時間點的值。</p> + +<p>一個 <code>Promise</code> 物件處於以下幾種狀態:</p> + +<ul> + <li><em>擱置(pending)</em>:初始狀態,不是 fulfilled 與 rejected。</li> + <li><em>實現(fulfilled)</em>:表示操作成功地完成。</li> + <li><em>拒絕(rejected)</em>:表示操作失敗了。</li> +</ul> + +<p>一個處於擱置狀態的 promise 能以一個值被實現(fulfilled),或是以一個原因或錯誤而被拒絕(rejected)。當上述任一狀態轉換發生時,那些透過 <code>then</code> 方法所繫結(associated)的處理函式列隊就會依序被調用。(若一個 promise 已被實現或拒絕,繫結(attached)於它的處理函式將立即被呼叫,因此完成非同步操作與繫結處理函式之間不存在競爭條件(race condition)。)</p> + +<p>由於 <code>{{jsxref("Promise.then", "Promise.prototype.then()")}}</code> 以及 <code>{{jsxref("Promise.catch", "Promise.prototype.catch()")}}</code> 方法都回傳 promise,它們可以被串接。</p> + +<p><img alt="" src="https://cdn.rawgit.com/Vectaio/a76330b025baf9bcdf07cb46e5a9ef9e/raw/26c4213a93dee1c39611dcd0ec12625811b20a26/js-promise.svg"></p> + +<div class="note"> +<p><strong>容易混淆:</strong> 許多其他語言擁有機制用來惰性求值(lazy evaluation)及延遲(deferring)運算,它們也被稱作“promises” — e.g. Scheme. 然而在 JavaScript 中 Promises 代表那些(已經)發生中(happening)的程序,它們可以繫結回呼函式。若您要找的是惰性求值表示式,考慮不帶參數的 <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">arrow function</a>:<code>f = () => <em>expression</em></code> 來建立惰性求值表示式,並透過 <code>f()</code> 進行求值.</p> +</div> + +<div class="note"> +<p><strong>Note</strong>: 一個被實現或拒絕,但不處於 pending 的 promise 被稱作被解決(settled)。您也會見到使用解決(resolved)一詞來描述 promises — 這代表 promises 被實現(fulfilled)了。<a href="https://github.com/domenic/promises-unwrapping/blob/master/docs/states-and-fates.md">States and fates</a> 這篇文章包含了更多 promises 的專有名詞。</p> +</div> + +<h2 id="屬性">屬性</h2> + +<dl> + <dt><code>Promise.length</code></dt> + <dd>長度屬性,值固定為 <code>1</code>。(建構式參數數目).</dd> + <dt>{{jsxref("Promise.prototype")}}</dt> + <dd><code>Promise</code> 建構式的原型(prototype).</dd> +</dl> + +<h2 id="方法">方法</h2> + +<dl> + <dt>{{jsxref("Promise.all", "Promise.all(iterable)")}}</dt> + <dd>回傳一個 promise,當在引數 iterable 中所有 promises 都被實現時被實現,或在引數 iterable 中有一個 promise 被拒絕時立刻被拒絕。若回傳的 promise 被實現,它將以一個實現值的陣列被實現,其順序與 iterable 中的 promises 相同。若回傳的 promise 被拒絕,它將以失敗訊息被拒絕,此訊息來自第一個在 iterable 中被拒絕的 promise。這個方法在聚集許多 promises 的結果時很有效。</dd> + <dt>{{jsxref("Promise.race", "Promise.race(iterable)")}}</dt> + <dd>回傳一個被實現或拒絕的 promise,當 iterable 中有一個 promise 被實現或拒絕時。</dd> +</dl> + +<dl> + <dt>{{jsxref("Promise.reject", "Promise.reject(reason)")}}</dt> + <dd>回傳一個以失敗訊息拒絕的 <code>promise</code>。</dd> +</dl> + +<dl> + <dt>{{jsxref("Promise.resolve", "Promise.resolve(value)")}}</dt> + <dd>回傳一個以 value 實現的 <code>promise</code>。若該值為 thenable (i.e. 具有 <code>then</code> 方法),回傳的 promise 將跟隨(follow)之,採用她的最終狀態; 在其他情形回傳的 promise 將以 value 被實現。一般來說,當您不知道 value 是否為 promise,使用 {{jsxref("Promise.resolve", "Promise.resolve(value)")}},將回傳值以 promise 作處理。</dd> +</dl> + +<h2 id="Promise_原型"><code>Promise</code> 原型</h2> + +<h3 id="屬性_2">屬性</h3> + +<p>{{page('zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Promise/prototype','屬性')}}</p> + +<h3 id="方法_2">方法</h3> + +<p>{{page('zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Promise/prototype','方法')}}</p> + +<h2 id="建立_Promise">建立 Promise</h2> + +<p><code><font face="Open Sans, arial, x-locale-body, sans-serif">一個</font></code> <code>Promise</code> 物件透過 <code>new</code> 及其建構式建立。這個建構式接收一個叫作”執行器函式(executor function)“的引數。此函式接收兩個函式作為引數。第一個函式(<code>resolve)</code>在非同步作業成功完成時,以該作業之結果值被呼叫。第二個函式(<code>reject</code>)在作業失敗時,以失敗訊息,通常是一個 error object,被呼叫。</p> + +<pre class="brush: js">const myFirstPromise = new Promise((resolve, reject) => { + // 執行一些非同步作業,最終呼叫: + // + // resolve(someValue); // 實現 + // 或 + // reject("failure reason"); // 拒絕 +}); +</pre> + +<p>要提供一個函式 promise 功能,讓它回傳一個 promise 即可:</p> + +<pre class="brush: js">function myAsyncFunction(url) { + return new Promise((resolve, reject) => { + const xhr = new XMLHttpRequest(); + xhr.open("GET", url); + xhr.onload = () => resolve(xhr.responseText); + xhr.onerror = () => reject(xhr.statusText); + xhr.send(); + }); +};</pre> + +<h2 id="範例">範例</h2> + +<h3 id="入門範例">入門範例</h3> + +<pre class="brush: js">let myFirstPromise = new Promise((resolve, reject) => { + // 當非同步作業成功時,呼叫 resolve(...),而失敗時則呼叫 reject(...)。 + // 在這個例子中,使用 setTimeout(...) 來模擬非同步程式碼。 + // 在實務中,您將可能使用像是 XHR 或者一個 HTML5 API. + setTimeout(function(){ + resolve("Success!"); // Yay!非常順利! + }, 250); +}); + +myFirstPromise.then((successMessage) => { + // successMessage 是任何您由上方 resolve(...) 傳入的東西。 + // 在此僅作為成功訊息,但是它不一定是字串。 + console.log("Yay! " + successMessage); +}); +</pre> + +<h3 id="進階範例">進階範例</h3> + +<pre class="brush: html hidden"><button id="btn">Make a promise!</button> +<div id="log"></div> +</pre> + +<p><code>這個小範例演示了</code> <code>Promise</code> <code>的運作機制。每當 </code>{{HTMLElement("button")}} 被點擊時,<code>testPromise()</code> 方法被呼叫。每次點擊將透過 {{domxref("window.setTimeout()")}} 建立一個將在 1-3 秒內隨機地被實現的 promise,供 promise 計數(一個從 1 開始的數值)。建構式 <code>Promise()</code> 被用來建立 promise。</p> + +<p>promise 的實現值單純地經由一個實現回呼函式 {{jsxref("Promise.prototype.then()","p1.then()")}} 被印出。下以一些文字紀錄來展現方法中同步的與非同步處理 promise 的部分是如何分離彼此。</p> + +<pre class="brush: js">'use strict'; +var promiseCount = 0; + +function testPromise() { + let thisPromiseCount = ++promiseCount; + + let log = document.getElementById('log'); + log.insertAdjacentHTML('beforeend', thisPromiseCount + + ') Started (<small>Sync code started</small>)<br/>'); + + // 建立一個新的 promise:此 promise 承諾一個數值計數, 由 1 開始(等待約 2 秒) + let p1 = new Promise( + // 這個解決器函數(resolver function)呼叫實現或 + // 拒絕 promise。 + (resolve, reject) => { + log.insertAdjacentHTML('beforeend', thisPromiseCount + + ') Promise started (<small>Async code started</small>)<br/>'); + // 在此例子單純用來產生非同步特性。 + window.setTimeout( + function() { + // 實現這個 promise! + resolve(thisPromiseCount); + }, Math.random() * 2000 + 1000); + } + ); + + // 接著透過呼叫 then() 來決定 promise 進入 resolved 時,要透過 then() 做什麼, + // 或是進入 rejected 時,要透過 catch() 方法要做什麼。 + p1.then( + // 印出實現值(fulfillment value) + function(val) { + log.insertAdjacentHTML('beforeend', val + + ') Promise fulfilled (<small>Async code terminated</small>)<br/>'); + }) + .catch( + // 印出失敗訊息(rejection reason) + (reason) => { + console.log('Handle rejected promise ('+reason+') here.'); + }); + + log.insertAdjacentHTML('beforeend', thisPromiseCount + + ') Promise made (<small>Sync code terminated</small>)<br/>'); +}</pre> + +<p><sub>*譯註:resolver function 即 executor function。</sub></p> + +<pre class="brush:js hidden">if ("Promise" in window) { + let btn = document.getElementById("btn"); + btn.addEventListener("click",testPromise); +} else { + log = document.getElementById('log'); + log.innerHTML = "Live example not available as your browser doesn't support the <code>Promise<code> interface."; +} +</pre> + +<p>這個範例從點擊按鈕開始。您的瀏覽器需要支援 Promise。在短時間內點擊按鈕許多次,您甚至將看到不同的 promises 一個接一個地被實現。</p> + +<p>{{EmbedLiveSample("Advanced_Example", "500", "200")}}</p> + +<h2 id="使用_XHR_載入圖片">使用 XHR 載入圖片</h2> + +<p>另一個使用 <code>Promise</code> and <code><a href="/zh-TW/docs/Web/API/XMLHttpRequest">XMLHttpRequest</a></code> 來載入圖片的簡單例子可以在 MDN GitHub <a href="https://github.com/mdn/js-examples/tree/master/promises-test">js-examples</a> 儲存庫找到。 你也可以<a href="https://mdn.github.io/js-examples/promises-test/">see it in action</a>。每個步驟都附以註解,讓你能逐步遵隨 Promise 與 XHR 架構。</p> + +<h2 id="規範">規範</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-promise-objects', 'Promise')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition in an ECMA standard.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-promise-objects', 'Promise')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<p class="hidden">To contribute to this compatibility data, please write a pull request against this repository: <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a>.</p> + +<p>{{Compat("javascript.builtins.Promise")}}</p> + +<h2 id="參見">參見</h2> + +<ul> + <li><a href="/zh-TW/docs/Web/JavaScript/Guide/Using_promises">Using promises</a></li> + <li><a href="http://promisesaplus.com/">Promises/A+ specification</a></li> + <li><a href="https://medium.com/@ramsunvtech/promises-of-promise-part-1-53f769245a53">Venkatraman.R - JS Promise (Part 1, Basics)</a></li> + <li><a href="https://medium.com/@ramsunvtech/js-promise-part-2-q-js-when-js-and-rsvp-js-af596232525c#.dzlqh6ski">Venkatraman.R - JS Promise (Part 2 - Using Q.js, When.js and RSVP.js)</a></li> + <li><a href="https://tech.io/playgrounds/11107/tools-for-promises-unittesting/introduction">Venkatraman.R - Tools for Promises Unit Testing</a></li> + <li><a href="http://www.html5rocks.com/en/tutorials/es6/promises/">Jake Archibald: JavaScript Promises: There and Back Again</a></li> + <li><a href="http://de.slideshare.net/domenicdenicola/callbacks-promises-and-coroutines-oh-my-the-evolution-of-asynchronicity-in-javascript">Domenic Denicola: Callbacks, Promises, and Coroutines – Asynchronous Programming Patterns in JavaScript</a></li> + <li><a href="http://www.mattgreer.org/articles/promises-in-wicked-detail/">Matt Greer: JavaScript Promises ... In Wicked Detail</a></li> + <li><a href="https://www.promisejs.org/">Forbes Lindesay: promisejs.org</a></li> + <li><a href="http://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html">Nolan Lawson: We have a problem with promises — Common mistakes with promises</a></li> + <li><a href="https://github.com/jakearchibald/es6-promise/">Promise polyfill</a></li> + <li><a href="https://www.udacity.com/course/javascript-promises--ud898">Udacity: JavaScript Promises</a></li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/promise/prototype/index.html b/files/zh-tw/web/javascript/reference/global_objects/promise/prototype/index.html new file mode 100644 index 0000000000..476c52f7a3 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/promise/prototype/index.html @@ -0,0 +1,64 @@ +--- +title: Promise.prototype +slug: Web/JavaScript/Reference/Global_Objects/Promise/prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Promise +--- +<div>{{JSRef}}</div> + +<p><code><strong>Promise</strong></code><strong><code>.prototype</code></strong> 屬性代表了 {{jsxref("Promise")}} 建構式的原型物件。</p> + +<div>{{js_property_attributes(0,0,0)}}</div> + +<h2 id="描述">描述</h2> + +<p>所有 {{jsxref("Promise")}} 實例都繼承自 {{jsxref("Promise.prototype")}}。您可以使用建構式的原型物件來增加屬性或方法到所有的 <code>Promise</code> 實例。</p> + +<h2 id="屬性">屬性</h2> + +<dl> + <dt><code>Promise.prototype.constructor</code></dt> + <dd>回傳一個建立實例原型(instance's prototype)的函式。預設為 {{jsxref("Promise")}} 函數。</dd> +</dl> + +<h2 id="方法">方法</h2> + +<dl> + <dt>{{jsxref("Promise.catch", "Promise.prototype.catch(onRejected)")}}</dt> + <dd>繫結一個拒絕回呼函式(rejection handler callback)到 promise,當它被呼叫時回傳一個以回傳值作解析的新 promise,或者當 promise 被實現時以原值作解析。</dd> + <dt>{{jsxref("Promise.then", "Promise.prototype.then(onFulfilled, onRejected)")}}</dt> + <dd>繫結實現或拒絕回呼函式到 promise,回傳一個以 handler 之回傳值作解析的新 promise,或者當 promise 未處理(not handled)時以原值作解析。(i.e. 比如相關聯的 <code>onFulfilled</code> 或 <code>onRejected</code> 不是函式。)</dd> +</dl> + +<h2 id="規範">規範</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-promise.prototype', 'Promise.prototype')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-promise.prototype', 'Promise.prototype')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<p class="hidden">To contribute to this compatibility data, please write a pull request against this file: <a href="https://github.com/mdn/browser-compat-data/blob/master/javascript/promise.json">https://github.com/mdn/browser-compat-data/blob/master/javascript/promise.json</a>.</p> + +<p>{{Compat("javascript/promise","Promise.prototype")}}</p> + +<h2 id="參見">參見</h2> + +<ul> + <li>{{jsxref("Promise")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/promise/race/index.html b/files/zh-tw/web/javascript/reference/global_objects/promise/race/index.html new file mode 100644 index 0000000000..9f0d8b4d2e --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/promise/race/index.html @@ -0,0 +1,171 @@ +--- +title: Promise.race() +slug: Web/JavaScript/Reference/Global_Objects/Promise/race +translation_of: Web/JavaScript/Reference/Global_Objects/Promise/race +--- +<div>{{JSRef}}</div> + +<p><code><strong>Promise.race(iterable)</strong></code> 方法回傳一個 promise 物件,此 promise 物件會於 iterable 引數中任一個 promise 轉為 resolve 或 rejected 時立即轉變成 resolve 或 rejected,並且接收其成功值或失敗訊息。</p> + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox"><var>Promise.race(iterable)</var>;</pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt>iterable</dt> + <dd>一個 iterable 物件,像是 {{jsxref("Array")}}. 請參考<a href="/zh-TW/docs/Web/JavaScript/Reference/Iteration_protocols#可迭代協議">可迭代協議</a>。</dd> +</dl> + +<h3 id="回傳值">回傳值</h3> + +<p>當傳入的 iterable 中有 promise 被實現或拒絕時,立刻回傳被實現或拒絕的 {{jsxref("Promise")}}。</p> + +<h2 id="描述">描述</h2> + +<p><code>race</code> 函式回傳一個與傳入的 iterable 之中第一個被解決(settled)的 promise 相同方式被解決(且以相同值)的 <code>Promise</code>。</p> + +<h2 id="範例">範例</h2> + +<h3 id="Promise.race_的非同步性質"><font face="consolas, Liberation Mono, courier, monospace"><code>Promise.race</code> 的非同步性質</font></h3> + +<p><code><font face="Open Sans, arial, x-locale-body, sans-serif">以下例子演示了 </font>Promise.race</code> <code>的非同步性質:</code></p> + +<pre class="brush: js">// we are passing as argument an array of promises that are already resolved, +// to trigger Promise.race as soon as possible +var resolvedPromisesArray = [Promise.resolve(33), Promise.resolve(44)]; + +var p = Promise.race(resolvedPromisesArray); +// immediately logging the value of p +console.log(p); + +// using setTimeout we can execute code after the stack is empty +setTimeout(function(){ + console.log('the stack is now empty'); + console.log(p); +}); + +// logs, in order: +// Promise { <state>: "pending" } +// the stack is now empty +// Promise { <state>: "fulfilled", <value>: 33 }</pre> + +<p>一個空的 iterable 造成回傳的 promise 永久擱置:</p> + +<pre class="brush: js">var foreverPendingPromise = Promise.race([]); +console.log(foreverPendingPromise); +setTimeout(function(){ + console.log('the stack is now empty'); + console.log(foreverPendingPromise); +}); + +// logs, in order: +// Promise { <state>: "pending" } +// the stack is now empty +// Promise { <state>: "pending" } +</pre> + +<p>若 iterable 中有一個或多個非 promise 值且/或一個已經被實現/解決的 promise,<code>Promise.race</code> 將以陣列中第一個這樣的值解決:</p> + +<pre class="brush: js">var foreverPendingPromise = Promise.race([]); +var alreadyResolvedProm = Promise.resolve(666); + +var arr = [foreverPendingPromise, alreadyResolvedProm, "non-Promise value"]; +var arr2 = [foreverPendingPromise, "non-Promise value", Promise.resolve(666)]; +var p = Promise.race(arr); +var p2 = Promise.race(arr2); + +console.log(p); +console.log(p2); +setTimeout(function(){ + console.log('the stack is now empty'); + console.log(p); + console.log(p2); +}); + +// logs, in order: +// Promise { <state>: "pending" } +// Promise { <state>: "pending" } +// the stack is now empty +// Promise { <state>: "fulfilled", <value>: 666 } +// Promise { <state>: "fulfilled", <value>: "non-Promise value" } +</pre> + +<h3 id="使用_Promise.race_–_及_setTimeout_的範例">使用 <code>Promise.race</code> – 及 <code><a href="/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout">setTimeout</a></code> 的範例</h3> + +<pre class="brush: js">var p1 = new Promise(function(resolve, reject) { + setTimeout(resolve, 500, 'one'); +}); +var p2 = new Promise(function(resolve, reject) { + setTimeout(resolve, 100, 'two'); +}); + +Promise.race([p1, p2]).then(function(value) { + console.log(value); // "two" + // Both resolve, but p2 is faster +}); + +var p3 = new Promise(function(resolve, reject) { + setTimeout(resolve, 100, 'three'); +}); +var p4 = new Promise(function(resolve, reject) { + setTimeout(reject, 500, 'four'); +}); + +Promise.race([p3, p4]).then(function(value) { + console.log(value); // "three" + // p3 is faster, so it resolves +}, function(reason) { + // Not called +}); + +var p5 = new Promise(function(resolve, reject) { + setTimeout(resolve, 500, 'five'); +}); +var p6 = new Promise(function(resolve, reject) { + setTimeout(reject, 100, 'six'); +}); + +Promise.race([p5, p6]).then(function(value) { + // Not called +}, function(reason) { + console.log(reason); // "six" + // p6 is faster, so it rejects +}); +</pre> + +<h2 id="規範">規範</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-promise.race', 'Promise.race')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition in an ECMA standard.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-promise.race', 'Promise.race')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Promise.race")}}</p> + +<h2 id="參見">參見</h2> + +<ul> + <li>{{jsxref("Promise")}}</li> + <li>{{jsxref("Promise.all()")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/promise/reject/index.html b/files/zh-tw/web/javascript/reference/global_objects/promise/reject/index.html new file mode 100644 index 0000000000..0c41a37509 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/promise/reject/index.html @@ -0,0 +1,72 @@ +--- +title: Promise.reject() +slug: Web/JavaScript/Reference/Global_Objects/Promise/reject +translation_of: Web/JavaScript/Reference/Global_Objects/Promise/reject +--- +<div>{{JSRef}}</div> + +<p><code><strong>Promise.reject(reason)</strong></code><strong> </strong>方法回傳一個以 <code>reason</code> 拒絕的 <code>Promise</code> 物件。</p> + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox"><var>Promise.reject(reason)</var>;</pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt>reason</dt> + <dd><code>Promise</code> 的失敗訊息。</dd> +</dl> + +<h3 id="回傳值">回傳值</h3> + +<p>一個以 <code>reason</code> 拒絕的 {{jsxref("Promise")}}。</p> + +<h2 id="描述">描述</h2> + +<p>靜態函式 <code>Promise.reject</code> 回傳一個被拒絕的 <code>Promise。由於除錯目的及選擇性錯誤捕捉(selective error catching),使</code>用一個 <code>instanceof</code> {{jsxref("Error")}} 作為 reason 是很有幫助的。</p> + +<h2 id="範例">範例</h2> + +<h3 id="使用靜態方法_Promise.reject()">使用靜態方法 Promise.reject()</h3> + +<pre class="brush: js">Promise.reject(new Error('fail')).then(function(error) { + // not called +}, function(error) { + console.log(error); // Stacktrace +});</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-promise.reject', 'Promise.reject')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition in an ECMA standard.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-promise.reject', 'Promise.reject')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p class="hidden">To contribute to this compatibility data, please write a pull request against this repository: <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a>.</p> + +<p>{{Compat("javascript.builtins.Promise.reject")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Promise")}}</li> + <li><a href="https://github.com/petkaantonov/bluebird#error-handling">Selective error catching using the BlueBird Promise library</a></li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/promise/resolve/index.html b/files/zh-tw/web/javascript/reference/global_objects/promise/resolve/index.html new file mode 100644 index 0000000000..e2d460a7e3 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/promise/resolve/index.html @@ -0,0 +1,142 @@ +--- +title: Promise.resolve() +slug: Web/JavaScript/Reference/Global_Objects/Promise/resolve +translation_of: Web/JavaScript/Reference/Global_Objects/Promise/resolve +--- +<div>{{JSRef}}</div> + +<p><code><strong>Promise.resolve(value)</strong></code> 方法回傳一個以 value 判定結果的 {{jsxref("Promise")}} 物件。若 value 是個 thenable (例如,具有 {{jsxref("Promise.then", "\"then\"方法")}}),則回傳的 promise 將依其結果採取其最終狀態;若 value 是 promise,則作為呼叫 Promise.resolve 之結果;其他情形都將回傳以 value 實現的 promise。</p> + +<h2 id="語法">語法</h2> + +<pre class="brush: js">Promise.resolve(value); +Promise.resolve(promise); +Promise.resolve(thenable); +</pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt>value</dt> + <dd>將被 <code>Promise</code> 實現的引數(argument)。可以是個 <code>Promise</code> 或待解決的 thenable。</dd> +</dl> + +<h3 id="回傳值">回傳值</h3> + +<p>以 value 或作為 value 的 promise 解決的 {{jsxref("Promise")}}。</p> + +<h2 id="描述">描述</h2> + +<p><code>靜態函式</code> <code>Promise.resolve</code> 回傳判定後的 <code>Promise。</code></p> + +<h2 id="範例">範例</h2> + +<h3 id="使用_Promise.resolve_靜態方法">使用 <code>Promise.resolve</code> 靜態方法</h3> + +<pre class="brush: js">Promise.resolve('Success').then(function(value) { + console.log(value); // "Success" +}, function(value) { + // not called +}); +</pre> + +<h3 id="判定陣列">判定陣列</h3> + +<pre class="brush: js">var p = Promise.resolve([1,2,3]); +p.then(function(v) { + console.log(v[0]); // 1 +}); +</pre> + +<h3 id="判定另一個_Promise">判定另一個 <code>Promise</code></h3> + +<pre class="brush: js">var original = Promise.resolve(33); +var cast = Promise.resolve(original); +cast.then(function(value) { + console.log('value: ' + value); +}); +console.log('original === cast ? ' + (original === cast)); + +// logs, in order: +// original === cast ? true +// value: 33 +</pre> + +<p>由於 handlers 是非同步地被調用而導致相反的紀錄順序。經由<a href="https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Promise/then#回傳值">這篇文章</a>了解 then 如何運作。</p> + +<h3 id="判定_thenables_及拋出_Errors">判定 thenables 及拋出 Errors</h3> + +<pre class="brush: js">// Resolving a thenable object +var p1 = Promise.resolve({ + then: function(onFulfill, onReject) { onFulfill('fulfilled!'); } +}); +console.log(p1 instanceof Promise) // true, object casted to a Promise + +p1.then(function(v) { + console.log(v); // "fulfilled!" + }, function(e) { + // not called +}); + +// Thenable throws before callback +// Promise rejects +var thenable = { then: function(resolve) { + throw new TypeError('Throwing'); + resolve('Resolving'); +}}; + +var p2 = Promise.resolve(thenable); +p2.then(function(v) { + // not called +}, function(e) { + console.log(e); // TypeError: Throwing +}); + +// Thenable throws after callback +// Promise resolves +var thenable = { then: function(resolve) { + resolve('Resolving'); + throw new TypeError('Throwing'); +}}; + +var p3 = Promise.resolve(thenable); +p3.then(function(v) { + console.log(v); // "Resolving" +}, function(e) { + // not called +}); +</pre> + +<h2 id="規範">規範</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-promise.resolve', 'Promise.resolve')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition in an ECMA standard.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-promise.resolve', 'Promise.resolve')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<p class="hidden">To contribute to this compatibility data, please write a pull request against this repository: <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a>.</p> + +<p>{{Compat("javascript.builtins.Promise.resolve")}}</p> + +<h2 id="參見">參見</h2> + +<ul> + <li>{{jsxref("Promise")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/promise/then/index.html b/files/zh-tw/web/javascript/reference/global_objects/promise/then/index.html new file mode 100644 index 0000000000..19682d0199 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/promise/then/index.html @@ -0,0 +1,271 @@ +--- +title: Promise.prototype.then() +slug: Web/JavaScript/Reference/Global_Objects/Promise/then +translation_of: Web/JavaScript/Reference/Global_Objects/Promise/then +--- +<div>{{JSRef}}</div> + +<p><strong><code>then()</code> </strong>方法回傳一個 {{domxref("Promise")}} 物件。它接收兩個引數: <code>Promise</code> 在成功及失敗情況時的回呼函式。</p> + +<div class="note"> +<p>如果有一個或兩個引數被省略,或為非函式(non-functions),則 <code>then</code> 將處於遺失 handler(s) 的狀態,但不會產生錯誤。若發起 <code>then</code> 之 <code>Promise</code> 採取了一個狀態(實現(<code>fulfillment)</code>或拒絕(<code>rejection))</code>而 <code>then</code> 沒有處理它的函式,一個不具有額外 handlers 的新 <code>Promise</code> 物件將被建立,單純採取原 <code>Promise</code> 其最終狀態。</p> +</div> + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox"><var>p.then(onFulfilled[, onRejected])</var>; + +p.then(function(value) { + // fulfillment +}, function(reason) { + // rejection +}); +</pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>onFulfilled</code></dt> + <dd>一個 {{jsxref("Function")}},當 <code>Promise</code> 被實現(fulfilled)時被呼叫。此函式接收一個實現值(<code>fullfillment value)作為引數。</code></dd> + <dt><code>onRejected </code>{{optional_inline}}</dt> + <dd>一個 {{jsxref("Function")}},當 <code>Promise</code> 被拒絕(rejected)時被呼叫。此函式接收一個失敗訊息(<code>rejection reason)作為引數。</code></dd> +</dl> + +<h3 id="回傳值">回傳值</h3> + +<p>一個進入<strong>擱置(pending)</strong>狀態的 {{jsxref("Promise")}}。(只要堆疊一空)handler 函式<strong>非同步地(asynchronously)</strong>被呼叫。在調用 handler 後,若 handler 函式:</p> + +<ul> + <li>回傳一個值,則 <code>then</code> 回傳之 promise 以此值被實現(resolved)。</li> + <li>拋出一個例外,則 <code>then</code> 回傳之 promise 以此例外被否決(rejected)。</li> + <li>回傳一個被實現的 promise,則 <code>then</code> 回傳之 promise 以此值被實現。</li> + <li>回傳一個被否決的 promise,則 <code>then</code> 回傳之 promise 以此值被否決。</li> + <li>回傳另一個被<strong>擱置</strong>的 promise 物件,則 <code>then</code> 回傳之 promise 之實現/拒絕隨後由處理函式之實現/否決決定。並且,<code>then</code> 回傳之 promise 將與處理函式回傳之 promise 以相同值被解決。</li> +</ul> + +<p>以下例子展示 <code>then</code> 方法的非同步性質(asynchronicity)。</p> + +<pre class="brush: js">// 使用一個已實現的 promise,'then' 區塊將立即被觸發,但是它的 handlers 將是非同步地被觸發,如同 console.logs 所示 +var resolvedProm = Promise.resolve(33); + +var thenProm = resolvedProm.then(function(value){ + console.log("我在 main stack 之後被呼叫。收到及將回傳的值為:" + value); + return value; +}); +// 立即紀錄 thenProm +console.log(thenProm); + +// 我們可以使用 setTimeout 以延遲(postpone)函式執行直到堆疊為空 +setTimeout(function(){ + console.log(thenProm); +}); + + +// 紀錄結果,依序為: +// Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined} +// "我在 main stack 之後被呼叫。收到及將回傳的值為:33" +// Promise {[[PromiseStatus]]: "resolved", [[PromiseValue]]: 33} +</pre> + +<h2 id="描述">描述</h2> + +<p>因為 <code>then</code> 和 {{jsxref("Promise.prototype.catch()")}} 方法都回傳 promises,它們可以被串接 — 稱為組合(<em>composition)。</em></p> + +<h2 id="範例">範例</h2> + +<h3 id="運用_then_方法">運用 <code>then</code> 方法</h3> + +<pre class="brush: js">var p1 = new Promise( (resolve, reject) => { + resolve('Success!'); + // or + // reject ("Error!"); +} ); + +p1.then( value => { + console.log(value); // Success! +}, reason => { + console.log(reason); // Error! +} ); +</pre> + +<h3 id="串接">串接</h3> + +<p><code>then</code> 方法回傳一個 <code>Promise</code> 而可以進行方法串接(method chaining)。</p> + +<p>如果傳入 <code>then</code> 的 handler 函式回傳一個 promise,一個等價的 <code>Promise</code> 將被展現給方法串接中的下一個 then 。以下程式碼片段透過 <code>setTimout</code> 函式模擬非同步程式碼。</p> + +<pre class="brush: js">Promise.resolve('foo') + // 1. Receive "foo" concatenate "bar" to it and resolve that to the next then + .then(function(string) { + return new Promise(function(resolve, reject) { + setTimeout(function() { + string += 'bar'; + resolve(string); + }, 1); + }); + }) + // 2. receive "foobar", register a callback function to work on that string + // and print it to the console, but not before return the unworked on + // string to the next then + .then(function(string) { + setTimeout(function() { + string += 'baz'; + console.log(string); + }, 1) + return string; + }) + // 3. print helpful messages about how the code in this section will be run + // before string is actually processed by the mocked asynchronous code in the + // prior then block. + .then(function(string) { + console.log("Last Then: oops... didn't bother to instantiate and return " + + "a promise in the prior then so the sequence may be a bit " + + "surprising"); + + // Note that `string` will not have the 'baz' bit of it at this point. This + // is because we mocked that to happen asynchronously with a setTimeout function + console.log(string); + });</pre> + +<p>當 handler 僅回傳一個值,實際上它將回傳 <code>Promise.resolve(<value returned by whichever handler was called>)</code>.</p> + +<pre class="brush: js">var p2 = new Promise(function(resolve, reject) { + resolve(1); +}); + +p2.then(function(value) { + console.log(value); // 1 + return value + 1; +}).then(function(value) { + console.log(value + '- This synchronous usage is virtually pointless'); // 2- This synchronous usage is virtually pointless +}); + +p2.then(function(value) { + console.log(value); // 1 +}); +</pre> + +<p>若函式拋出一個錯誤或回傳一個被否決的 Promise,<code>then</code> 也將回傳一個被否決的 Promise。</p> + +<pre class="brush: js">Promise.resolve() + .then( () => { + // 使 .then() 回傳一個被否決的 Promise + throw 'Oh no!'; + }) + .then( () => { + console.log( 'Not called.' ); + }, reason => { + console.error( 'onRejected function called: ', reason ); + });</pre> + +<p>在所有其他情形,實現中的 Promise 被回傳。在以下例子中,第一個 <code>then()</code> 將回傳一個實現中包裹 42 的 promise,即使串接中的前一個 Promise 被否決。</p> + +<pre class="brush: js">Promise.reject() + .then( () => 99, () => 42 ) // onRejected returns 42 which is wrapped in a resolving Promise + .then( solution => console.log( 'Resolved with ' + solution ) ); // Resolved with 42</pre> + +<p>實務上,使用 <code>catch</code> 捕捉被否決的 promise 較理想的,而不建議使用兩個引數 <code>then</code> 語法,如下展示。</p> + +<pre class="brush: js">Promise.resolve() + .then( () => { + // Makes .then() return a rejected promise + throw 'Oh no!'; + }) + .catch( reason => { + console.error( 'onRejected function called: ', reason ); + }) + .then( () => { + console.log( "I am always called even if the prior then's promise rejects" ); + });</pre> + +<p><br> + 你也可以透過串接實作一個 Promise-based API 函式,基於它本身。</p> + +<pre class="brush: js">function fetch_current_data() { + // The <a href="/en-US/docs/Web/API/GlobalFetch/fetch">fetch</a>() API returns a Promise. This function + // exposes a similar API, except the fulfillment + // value of this function's Promise has had more + // work done on it. + return fetch('current-data.json').then((response) => { + if (response.headers.get('content-type') != 'application/json') { + throw new TypeError(); + } + var j = response.json(); + // maybe do something with j + return j; // fulfillment value given to user of + // fetch_current_data().then() + }); +} +</pre> + +<p>若 <code>onFulfilled</code> 回傳一個 promise,則 <code>then</code> 的實現/否決將取決它。</p> + +<pre class="brush: js">function resolveLater(resolve, reject) { + setTimeout(function () { + resolve(10); + }, 1000); +} +function rejectLater(resolve, reject) { + setTimeout(function () { + reject(20); + }, 1000); +} + +var p1 = Promise.resolve('foo'); +var p2 = p1.then(function() { + // Return promise here, that will be resolved to 10 after 1 second + return new Promise(resolveLater); +}); +p2.then(function(v) { + console.log('resolved', v); // "resolved", 10 +}, function(e) { + // not called + console.log('rejected', e); +}); + +var p3 = p1.then(function() { + // Return promise here, that will be rejected with 20 after 1 second + return new Promise(rejectLater); +}); +p3.then(function(v) { + // not called + console.log('resolved', v); +}, function(e) { + console.log('rejected', e); // "rejected", 20 +}); +</pre> + +<h2 id="規範">規範</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-promise.prototype.then', 'Promise.prototype.then')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition in an ECMA standard.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-promise.prototype.then', 'Promise.prototype.then')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<p class="hidden">To contribute to this compatibility data, please write a pull request against this file: <a href="https://github.com/mdn/browser-compat-data/blob/master/javascript/promise.json">https://github.com/mdn/browser-compat-data/blob/master/javascript/promise.json</a>.</p> + +<p>{{Compat("javascript/promise","Promise.prototype.then")}}</p> + +<h2 id="參見">參見</h2> + +<ul> + <li>{{jsxref("Promise")}}</li> + <li>{{jsxref("Promise.prototype.catch()")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/proxy/index.html b/files/zh-tw/web/javascript/reference/global_objects/proxy/index.html new file mode 100644 index 0000000000..54a71be888 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/proxy/index.html @@ -0,0 +1,400 @@ +--- +title: Proxy +slug: Web/JavaScript/Reference/Global_Objects/Proxy +tags: + - Class + - ECMAScript 2015 + - JavaScript + - Proxy +translation_of: Web/JavaScript/Reference/Global_Objects/Proxy +--- +<div> +<div>{{JSRef}}</div> +</div> + +<p><strong>Proxy</strong> 物件被使用於定義基本操作的自定行為(例如:尋找屬性、賦值、列舉、函式調用等等)。</p> + +<h2 id="術語">術語</h2> + +<dl> + <dt><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/handler">handler</a></dt> + <dd>Placeholder object which contains traps.</dd> + <dt>traps</dt> + <dd>The methods that provide property access. This is analogous to the concept of traps in operating systems.</dd> + <dt>target</dt> + <dd>Object which the proxy virtualizes. It is often used as storage backend for the proxy. Invariants (semantics that remain unchanged) regarding object non-extensibility or non-configurable properties are verified against the target.</dd> +</dl> + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox notranslate">var p = new Proxy(target, handler); +</pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>target</code></dt> + <dd>A target object (can be any sort of object, including a native array, a function or even another proxy) to wrap with <code>Proxy</code>.</dd> + <dt><code>handler</code></dt> + <dd>An object whose properties are functions which define the behavior of the proxy when an operation is performed on it.</dd> +</dl> + +<h2 id="方法">方法</h2> + +<dl> + <dt>{{jsxref("Proxy.revocable()")}}</dt> + <dd>Creates a revocable <code>Proxy</code> object.</dd> +</dl> + +<h2 id="Methods_of_the_handler_object">Methods of the handler object</h2> + +<p>The handler object is a placeholder object which contains traps for <code>Proxy</code>.</p> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/handler', 'Methods') }}</div> + +<h2 id="範例">範例</h2> + +<h3 id="Basic_example">Basic example</h3> + +<p>In this simple example the number <code>37</code> gets returned as the default value when the property name is not in the object. It is using the <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/handler/get"><code>get</code></a> handler.</p> + +<pre class="brush: js notranslate">var handler = { + get: function(target, name) { + return name in target ? + target[name] : + 37; + } +}; + +var p = new Proxy({}, handler); +p.a = 1; +p.b = undefined; + +console.log(p.a, p.b); // 1, undefined +console.log('c' in p, p.c); // false, 37 +</pre> + +<h3 id="No-op_forwarding_proxy">No-op forwarding proxy</h3> + +<p>In this example, we are using a native JavaScript object to which our proxy will forward all operations that are applied to it.</p> + +<pre class="brush: js notranslate">var target = {}; +var p = new Proxy(target, {}); + +p.a = 37; // operation forwarded to the target + +console.log(target.a); // 37. The operation has been properly forwarded +</pre> + +<h3 id="Validation">Validation</h3> + +<p>With a <code>Proxy</code>, you can easily validate the passed value for an object. This example uses the <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/handler/set"><code>set</code></a> handler.</p> + +<pre class="brush: js notranslate">let validator = { + set: function(obj, prop, value) { + if (prop === 'age') { + if (!Number.isInteger(value)) { + throw new TypeError('The age is not an integer'); + } + if (value > 200) { + throw new RangeError('The age seems invalid'); + } + } + + // The default behavior to store the value + obj[prop] = value; + + // Indicate success + return true; + } +}; + +let person = new Proxy({}, validator); + +person.age = 100; +console.log(person.age); // 100 +person.age = 'young'; // Throws an exception +person.age = 300; // Throws an exception</pre> + +<h3 id="Extending_constructor">Extending constructor</h3> + +<p>A function proxy could easily extend a constructor with a new constructor. This example uses the <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/handler/construct"><code>construct</code></a> and <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/handler/apply"><code>apply</code></a> handlers.</p> + +<pre class="brush: js notranslate">function extend(sup, base) { + var descriptor = Object.getOwnPropertyDescriptor( + base.prototype, 'constructor' + ); + base.prototype = Object.create(sup.prototype); + var handler = { + construct: function(target, args) { + var obj = Object.create(base.prototype); + this.apply(target, obj, args); + return obj; + }, + apply: function(target, that, args) { + sup.apply(that, args); + base.apply(that, args); + } + }; + var proxy = new Proxy(base, handler); + descriptor.value = proxy; + Object.defineProperty(base.prototype, 'constructor', descriptor); + return proxy; +} + +var Person = function(name) { + this.name = name; +}; + +var Boy = extend(Person, function(name, age) { + this.age = age; +}); + +Boy.prototype.sex = 'M'; + +var Peter = new Boy('Peter', 13); +console.log(Peter.sex); // "M" +console.log(Peter.name); // "Peter" +console.log(Peter.age); // 13</pre> + +<h3 id="Manipulating_DOM_nodes">Manipulating DOM nodes</h3> + +<p>Sometimes you want to toggle the attribute or class name of two different elements. Here's how using the <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/handler/set"><code>set</code></a> handler.</p> + +<pre class="brush: js notranslate">let view = new Proxy({ + selected: null +}, +{ + set: function(obj, prop, newval) { + let oldval = obj[prop]; + + if (prop === 'selected') { + if (oldval) { + oldval.setAttribute('aria-selected', 'false'); + } + if (newval) { + newval.setAttribute('aria-selected', 'true'); + } + } + + // The default behavior to store the value + obj[prop] = newval; + + // Indicate success + return true; + } +}); + +let i1 = view.selected = document.getElementById('item-1'); +console.log(i1.getAttribute('aria-selected')); // 'true' + +let i2 = view.selected = document.getElementById('item-2'); +console.log(i1.getAttribute('aria-selected')); // 'false' +console.log(i2.getAttribute('aria-selected')); // 'true'</pre> + +<h3 id="Value_correction_and_an_extra_property">Value correction and an extra property</h3> + +<p>The <code>products</code> proxy object evaluates the passed value and convert it to an array if needed. The object also supports an extra property called <code>latestBrowser</code> both as a getter and a setter.</p> + +<pre class="brush: js notranslate">let products = new Proxy({ + browsers: ['Internet Explorer', 'Netscape'] +}, +{ + get: function(obj, prop) { + // An extra property + if (prop === 'latestBrowser') { + return obj.browsers[obj.browsers.length - 1]; + } + + // The default behavior to return the value + return obj[prop]; + }, + set: function(obj, prop, value) { + // An extra property + if (prop === 'latestBrowser') { + obj.browsers.push(value); + return true; + } + + // Convert the value if it is not an array + if (typeof value === 'string') { + value = [value]; + } + + // The default behavior to store the value + obj[prop] = value; + + // Indicate success + return true; + } +}); + +console.log(products.browsers); // ['Internet Explorer', 'Netscape'] +products.browsers = 'Firefox'; // pass a string (by mistake) +console.log(products.browsers); // ['Firefox'] <- no problem, the value is an array + +products.latestBrowser = 'Chrome'; +console.log(products.browsers); // ['Firefox', 'Chrome'] +console.log(products.latestBrowser); // 'Chrome'</pre> + +<h3 id="Finding_an_array_item_object_by_its_property">Finding an array item object by its property</h3> + +<p>This proxy extends an array with some utility features. As you see, you can flexibly "define" properties without using <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperties"><code>Object.defineProperties</code></a>. This example can be adapted to find a table row by its cell. In that case, the target will be <a href="/en-US/docs/DOM/table.rows"><code>table.rows</code></a>.</p> + +<pre class="brush: js notranslate">let products = new Proxy([ + { name: 'Firefox', type: 'browser' }, + { name: 'SeaMonkey', type: 'browser' }, + { name: 'Thunderbird', type: 'mailer' } +], +{ + get: function(obj, prop) { + // The default behavior to return the value; prop is usually an integer + if (prop in obj) { + return obj[prop]; + } + + // Get the number of products; an alias of products.length + if (prop === 'number') { + return obj.length; + } + + let result, types = {}; + + for (let product of obj) { + if (product.name === prop) { + result = product; + } + if (types[product.type]) { + types[product.type].push(product); + } else { + types[product.type] = [product]; + } + } + + // Get a product by name + if (result) { + return result; + } + + // Get products by type + if (prop in types) { + return types[prop]; + } + + // Get product types + if (prop === 'types') { + return Object.keys(types); + } + + return undefined; + } +}); + +console.log(products[0]); // { name: 'Firefox', type: 'browser' } +console.log(products['Firefox']); // { name: 'Firefox', type: 'browser' } +console.log(products['Chrome']); // undefined +console.log(products.browser); // [{ name: 'Firefox', type: 'browser' }, { name: 'SeaMonkey', type: 'browser' }] +console.log(products.types); // ['browser', 'mailer'] +console.log(products.number); // 3 +</pre> + +<h3 id="A_complete_traps_list_example">A complete <code>traps</code> list example</h3> + +<p>Now in order to create a complete sample <code>traps</code> list, for didactic purposes, we will try to proxify a <em>non native</em> object that is particularly suited to this type of operation: the <code>docCookies</code> global object created by <a href="https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie/Simple_document.cookie_framework" title="https://developer.mozilla.org/en-US/docs/DOM/document.cookie#A_little_framework.3A_a_complete_cookies_reader.2Fwriter_with_full_unicode_support">the "little framework" published on the <code>document.cookie</code> page</a>.</p> + +<pre class="brush: js notranslate">/* + var docCookies = ... get the "docCookies" object here: + https://developer.mozilla.org/en-US/docs/DOM/document.cookie#A_little_framework.3A_a_complete_cookies_reader.2Fwriter_with_full_unicode_support +*/ + +var docCookies = new Proxy(docCookies, { + get: function (oTarget, sKey) { + return oTarget[sKey] || oTarget.getItem(sKey) || undefined; + }, + set: function (oTarget, sKey, vValue) { + if (sKey in oTarget) { return false; } + return oTarget.setItem(sKey, vValue); + }, + deleteProperty: function (oTarget, sKey) { + if (sKey in oTarget) { return false; } + return oTarget.removeItem(sKey); + }, + enumerate: function (oTarget, sKey) { + return oTarget.keys(); + }, + ownKeys: function (oTarget, sKey) { + return oTarget.keys(); + }, + has: function (oTarget, sKey) { + return sKey in oTarget || oTarget.hasItem(sKey); + }, + defineProperty: function (oTarget, sKey, oDesc) { + if (oDesc && 'value' in oDesc) { oTarget.setItem(sKey, oDesc.value); } + return oTarget; + }, + getOwnPropertyDescriptor: function (oTarget, sKey) { + var vValue = oTarget.getItem(sKey); + return vValue ? { + value: vValue, + writable: true, + enumerable: true, + configurable: false + } : undefined; + }, +}); + +/* Cookies test */ + +console.log(docCookies.my_cookie1 = 'First value'); +console.log(docCookies.getItem('my_cookie1')); + +docCookies.setItem('my_cookie1', 'Changed value'); +console.log(docCookies.my_cookie1);</pre> + +<h2 id="規範">規範</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-proxy-objects', 'Proxy')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-proxy-objects', 'Proxy')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<p>{{Compat("javascript.builtins.Proxy", 2)}}</p> + +<h2 id="Gecko_specific_notes">Gecko specific notes</h2> + +<ul> + <li>At present, <code>Object.getPrototypeOf(proxy)</code> unconditionally returns <code>Object.getPrototypeOf(target)</code>, because the ES2015 getPrototypeOf trap is not yet implemented ({{bug(795904)}}, {{bug(888969)}}).</li> + <li><code>Array.isArray(proxy)</code> unconditionally returns <code>Array.isArray(target)</code> ({{bug(1096753)}}, {{bug(1111785)}}).</li> + <li><code>Object.prototype.toString.call(proxy)</code> unconditionally returns <code>Object.prototype.toString.call(target)</code>, because ES2015 Symbol.toStringTag is not yet implemented ({{bug(1114580)}}).</li> +</ul> + +<h2 id="參見">參見</h2> + +<ul> + <li><a class="external" href="https://www.youtube.com/watch?v=sClk6aB_CPk">"Proxies are awesome" Brendan Eich presentation at JSConf</a> (<a class="external" href="http://www.slideshare.net/BrendanEich/metaprog-5303821">slides</a>)</li> + <li><a class="external" href="http://wiki.ecmascript.org/doku.php?id=harmony:proxies">ECMAScript Harmony Proxy proposal page</a> and <a class="external" href="http://wiki.ecmascript.org/doku.php?id=harmony:proxies_semantics">ECMAScript Harmony proxy semantics page</a></li> + <li><a class="external" href="http://soft.vub.ac.be/~tvcutsem/proxies/">Tutorial on proxies</a></li> + <li><a href="/en-US/docs/JavaScript/Old_Proxy_API" title="/en-US/docs/JavaScript/Old_Proxy_API">SpiderMonkey specific Old Proxy API</a></li> + <li>{{jsxref("Object.watch()")}} is a non-standard feature but has been supported in Gecko for a long time.</li> +</ul> + +<h2 id="Licensing_note">Licensing note</h2> + +<p>Some content (text, examples) in this page has been copied or adapted from the <a class="external" href="http://wiki.ecmascript.org/doku.php">ECMAScript wiki</a> which content is licensed <a class="external" href="http://creativecommons.org/licenses/by-nc-sa/2.0/">CC 2.0 BY-NC-SA</a>.</p> diff --git a/files/zh-tw/web/javascript/reference/global_objects/rangeerror/index.html b/files/zh-tw/web/javascript/reference/global_objects/rangeerror/index.html new file mode 100644 index 0000000000..257c23be9a --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/rangeerror/index.html @@ -0,0 +1,152 @@ +--- +title: RangeError +slug: Web/JavaScript/Reference/Global_Objects/RangeError +tags: + - Error + - JavaScript + - Object + - RangeError +translation_of: Web/JavaScript/Reference/Global_Objects/RangeError +--- +<div>{{JSRef}}</div> + +<p><code><strong>RangeError</strong></code>物件在一個給定的值不在允許的集合或範圍內時被作為一個錯誤拋出</p> + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox"><code>new RangeError([<var>message</var>[, <var>fileName</var>[, <var>lineNumber</var>]]])</code></pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>message</code></dt> + <dd>可選。具人類可讀性的錯誤說明</dd> + <dt><code>fileName</code> {{non-standard_inline}}</dt> + <dd>可選。包含造成錯誤發生的程式碼的檔案名稱</dd> + <dt><code>lineNumber</code> {{non-standard_inline}}</dt> + <dd>可選。造成錯誤發生的程式碼行號</dd> +</dl> + +<h2 id="說明">說明</h2> + +<p>當試著往一個 function 傳入一個不被其允許的值作為參數時,一個<code>RangeError</code>被拋出。這可在多種情況遭遇到,例如傳入一個不被允許的字串值到 {{jsxref("String.prototype.normalize()")}},或試著透過 {{jsxref("Array")}} constructor 用一個不合法的長度來創建一個陣列,或往數值方法像是{{jsxref("Number.toExponential()")}}、{{jsxref("Number.toFixed()")}}、{{jsxref("Number.toPrecision()")}} 傳進糟糕的值。</p> + +<h2 id="屬性">屬性</h2> + +<dl> + <dt>{{jsxref("RangeError.prototype")}}</dt> + <dd>允許對一個 <code>RangeError</code> 物件增加其屬性。</dd> +</dl> + +<h2 id="方法">方法</h2> + +<p>普遍的 <code>RangeError</code> 自身沒有包含方法,儘管他的確從原型鍊中繼承了一些。</p> + +<h2 id="RangeError_物件實體"><code>RangeError</code> 物件實體</h2> + +<h3 id="屬性_2">屬性</h3> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/RangeError/prototype', 'Properties')}}</div> + +<h3 id="方法_2">方法</h3> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/RangeError/prototype', 'Methods')}}</div> + +<h2 id="範例">範例</h2> + +<h3 id="使用_RangeError_(數值)">使用 <code>RangeError</code> (數值)</h3> + +<pre class="brush: js">function check(n) +{ + if(!(n >= -500 && n <= 500)) + { + throw new RangeError("The argument must be between -500 and 500."); + } +} + +try +{ + check(2000); +} +catch(error) +{ + if(error instanceof RangeError) + { + // Handle the error. + } +}</pre> + +<h3 id="使用_RangeError_(非數值)">使用 <code>RangeError</code> (非數值)</h3> + +<pre class="brush: js">function check(value) +{ + if(["apple", "banana", "carrot"].includes(value) === false) + { + throw new RangeError("The argument must be an \"apple\", \"banana\", or \"carrot\"."); + } +} + +try +{ + check("cabbage"); +} +catch(error) +{ + if(error instanceof RangeError) + { + // Handle the error. + } +} +</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('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.11.6.2', 'RangeError')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-native-error-types-used-in-this-standard-rangeerror', 'RangeError')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-native-error-types-used-in-this-standard-rangeerror', 'RangeError')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<div> + + +<p>{{Compat("javascript.builtins.RangeError")}}</p> +</div> + +<h2 id="另見">另見</h2> + +<ul> + <li>{{jsxref("Error")}}</li> + <li>{{jsxref("RangeError.prototype")}}</li> + <li>{{jsxref("Array")}}</li> + <li>{{jsxref("Number.toExponential()")}}</li> + <li>{{jsxref("Number.toFixed()")}}</li> + <li>{{jsxref("Number.toPrecision()")}}</li> + <li>{{jsxref("String.prototype.normalize()")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/reflect/index.html b/files/zh-tw/web/javascript/reference/global_objects/reflect/index.html new file mode 100644 index 0000000000..4f1d980a0d --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/reflect/index.html @@ -0,0 +1,130 @@ +--- +title: Reflect +slug: Web/JavaScript/Reference/Global_Objects/Reflect +translation_of: Web/JavaScript/Reference/Global_Objects/Reflect +--- +<div>{{JSRef}}</div> + +<p><strong>Reflect</strong> 是一個內建物件,提供了用於獲取可截取之 JavaScript 操作的方法。這些方法與 <a href="/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Proxy/handler">proxy handlers</a> 的方法相同。<code>Reflect</code> 不是一個函式物件,因此它是不可建構的。</p> + +<h2 id="描述">描述</h2> + +<p>Unlike most global objects, <code>Reflect</code> is not a constructor. You can not use it with a <a href="/en-US/docs/Web/JavaScript/Reference/Operators/new"><code>new</code> operator</a> or invoke the <code>Reflect</code> object as a function. All properties and methods of <code>Reflect</code> are static (just like the {{jsxref("Math")}} object).</p> + +<h2 id="方法">方法</h2> + +<p>The <code>Reflect</code> object provides the following static functions which have the same names as the <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/handler">proxy handler methods</a>. Some of these methods are the same as corresponding methods on {{jsxref("Object")}}.</p> + +<dl> + <dt>{{jsxref("Reflect.apply()")}}</dt> + <dd>Calls a target function with arguments as specified by the <code>args</code> parameter. See also {{jsxref("Function.prototype.apply()")}}.</dd> + <dt>{{jsxref("Reflect.construct()")}}</dt> + <dd> The <a href="/en-US/docs/Web/JavaScript/Reference/Operators/new"><code>new</code> operator</a> as a function. Equivalent to calling <code>new target(...args)</code>.</dd> + <dt>{{jsxref("Reflect.defineProperty()")}}</dt> + <dd>Similar to {{jsxref("Object.defineProperty()")}}. Returns a {{jsxref("Boolean")}}.</dd> + <dt>{{jsxref("Reflect.deleteProperty()")}}</dt> + <dd>The <a href="/en-US/docs/Web/JavaScript/Reference/Operators/delete"><code>delete</code> operator</a> as a function. Equivalent to calling <code>delete target[name]</code>.</dd> + <dt>{{jsxref("Reflect.get()")}}</dt> + <dd>A function that returns the value of properties.</dd> + <dt>{{jsxref("Reflect.getOwnPropertyDescriptor()")}}</dt> + <dd>Similar to {{jsxref("Object.getOwnPropertyDescriptor()")}}. Returns a property descriptor of the given property if it exists on the object, {{jsxref("undefined")}} otherwise.</dd> + <dt>{{jsxref("Reflect.getPrototypeOf()")}}</dt> + <dd>Same as {{jsxref("Object.getPrototypeOf()")}}.</dd> + <dt>{{jsxref("Reflect.has()")}}</dt> + <dd>The <a href="/en-US/docs/Web/JavaScript/Reference/Operators/in"><code>in</code> operator</a> as function. Returns a boolean indicating whether an own or inherited property exists.</dd> + <dt>{{jsxref("Reflect.isExtensible()")}}</dt> + <dd>Same as {{jsxref("Object.isExtensible()")}}.</dd> + <dt>{{jsxref("Reflect.ownKeys()")}}</dt> + <dd>Returns an array of the target object's own (not inherited) property keys.</dd> + <dt>{{jsxref("Reflect.preventExtensions()")}}</dt> + <dd>Similar to {{jsxref("Object.preventExtensions()")}}. Returns a {{jsxref("Boolean")}}.</dd> + <dt>{{jsxref("Reflect.set()")}}</dt> + <dd>A function that assigns values to properties. Returns a {{jsxref("Boolean")}} that is <code>true</code> if the update was successful.</dd> + <dt>{{jsxref("Reflect.setPrototypeOf()")}}</dt> + <dd>A function that sets the prototype of an object.</dd> +</dl> + +<h2 id="規範">規範</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-reflect-object', 'Reflect')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-reflect-object', 'Reflect')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>Reflect.enumerate has been removed.</td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome(49.0)}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("42")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatSafari(10)}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome(49.0)}}</td> + <td>{{CompatChrome(49.0)}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("42")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatSafari(10)}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="參見">參見</h2> + +<ul> + <li>The {{jsxref("Proxy")}} global object.</li> + <li>The {{jsxref("Proxy.handler", "handler")}} object.</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/regexp/index.html b/files/zh-tw/web/javascript/reference/global_objects/regexp/index.html new file mode 100644 index 0000000000..7bf77316e2 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/regexp/index.html @@ -0,0 +1,269 @@ +--- +title: RegExp +slug: Web/JavaScript/Reference/Global_Objects/RegExp +translation_of: Web/JavaScript/Reference/Global_Objects/RegExp +--- +<div>{{JSRef}}</div> + +<div></div> + +<p><strong><code>RegExp</code></strong> 物件被用來比對符合自訂規則的文字。</p> + +<p>關於正規表達式(regular expressions)的介紹,可以閱讀 <a href="/zh-TW/docs/Web/JavaScript/Guide/Regular_Expressions">JavaScript 指南</a>中的 <a href="/zh-TW/docs/Web/JavaScript/Guide/Regular_Expressions">正規表達式章節</a>。</p> + +<h2 id="說明">說明</h2> + +<p>建立 <code>RegExp</code> 物件有兩種方式:<em>文字表示法 (literal notation)</em> 和 <em>建構子 (constructor)。</em></p> + +<ul> + <li><strong>文字表示法</strong> 的參數,頭尾以斜線標註,且不使用引號標註。</li> + <li><strong>建構子函式</strong> 的參數,頭尾不以斜線標註,但使用引號標註。</li> +</ul> + +<p>以下的表達式會建立出相同的正規表達式:</p> + +<pre class="brush: js">/ab+c/i +new RegExp(/ab+c/, 'i') // literal notation +new RegExp('ab+c', 'i') // constructor +</pre> + +<p>The literal notation provides a compilation of the regular expression when the expression is evaluated. Use literal notation when the regular expression will remain constant. For example, if you use literal notation to construct a regular expression used in a loop, the regular expression won't be recompiled on each iteration.</p> + +<p>The constructor of the regular expression object—for example, <code>new RegExp('ab+c')</code>—provides runtime compilation of the regular expression. Use the constructor function when you know the regular expression pattern will be changing, or you don't know the pattern and are getting it from another source, such as user input.</p> + +<p>Starting with ECMAScript 6, <code>new RegExp(/ab+c/, 'i')</code> no longer throws a {{jsxref("TypeError")}} ("can't supply flags when constructing one RegExp from another") when the first argument is a <code>RegExp</code> and the second <code><var>flags</var></code> argument is present. A new <code>RegExp</code> from the arguments is created instead.</p> + +<p>When using the constructor function, the normal string escape rules (preceding special characters with <code>\</code> when included in a string) are necessary.</p> + +<p>For example, the following are equivalent:</p> + +<pre class="brush: js">let re = /\w+/ +let re = new RegExp('\\w+') +</pre> + +<h2 id="Constructor">Constructor</h2> + +<dl> + <dt><code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/RegExp">RegExp()</a></code></dt> + <dd>Creates a regular expression object.</dd> +</dl> + +<h2 id="Properties">Properties</h2> + +<dl> + <dt><code>RegExp.prototype</code></dt> + <dd>Allows the addition of properties to all objects.</dd> + <dt><code>RegExp.length</code></dt> + <dd>The value of <code>RegExp.length</code> is <code>2</code>.</dd> + <dt>{{jsxref("RegExp.@@species", "get RegExp[@@species]")}}</dt> + <dd>The constructor function that is used to create derived objects.</dd> + <dt>{{jsxref("RegExp.lastIndex")}}</dt> + <dd>The index at which to start the next match.</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<p>The global <code>RegExp</code> object has no methods of its own. However, it does inherit some methods through the prototype chain.</p> + +<h2 id="RegExp_prototype_objects_and_instances"><code>RegExp</code> prototype objects and instances</h2> + +<h3 id="Properties_2">Properties</h3> + +<div> +<p>See also <a href="/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features#RegExp_Properties">deprecated <code>RegExp</code> properties.</a></p> + +<p>Note that several of the {{JSxRef("RegExp")}} properties have both long and short (Perl-like) names. Both names always refer to the same value. Perl is the programming language from which JavaScript modeled its regular expressions.</p> + +<dl> + <dt><code>RegExp.prototype.constructor</code></dt> + <dd>Specifies the function that creates an object's prototype.</dd> + <dt>{{JSxRef("RegExp.prototype.flags")}}</dt> + <dd>A string that contains the flags of the <code>RegExp</code> object.</dd> + <dt>{{JSxRef("RegExp.prototype.dotAll")}}</dt> + <dd>Whether <code>.</code> matches newlines or not.</dd> + <dt>{{JSxRef("RegExp.prototype.global")}}</dt> + <dd>Whether to test the regular expression against all possible matches in a string, or only against the first.</dd> + <dt>{{JSxRef("RegExp.prototype.ignoreCase")}}</dt> + <dd>Whether to ignore case while attempting a match in a string.</dd> + <dt>{{JSxRef("RegExp.prototype.multiline")}}</dt> + <dd>Whether or not to search in strings across multiple lines.</dd> + <dt>{{JSxRef("RegExp.prototype.source")}}</dt> + <dd>The text of the pattern.</dd> + <dt>{{JSxRef("RegExp.prototype.sticky")}}</dt> + <dd>Whether or not the search is sticky.</dd> + <dt>{{JSxRef("RegExp.prototype.unicode")}}</dt> + <dd>Whether or not Unicode features are enabled.</dd> +</dl> +</div> + +<h3 id="Methods_2">Methods</h3> + +<div> +<dl> + <dt>{{JSxRef("RegExp.prototype.compile()")}}</dt> + <dd>(Re-)compiles a regular expression during execution of a script.</dd> + <dt>{{JSxRef("RegExp.prototype.exec()")}}</dt> + <dd>Executes a search for a match in its string parameter.</dd> + <dt>{{JSxRef("RegExp.prototype.test()")}}</dt> + <dd>Tests for a match in its string parameter.</dd> + <dt>{{JSxRef("RegExp.prototype.@@match()", "RegExp.prototype[@@match]()")}}</dt> + <dd>Performs match to given string and returns match result.</dd> + <dt>{{JSxRef("RegExp.prototype.@@matchAll()", "RegExp.prototype[@@matchAll]()")}}</dt> + <dd>Returns all matches of the regular expression against a string.</dd> + <dt>{{JSxRef("RegExp.prototype.@@replace()", "RegExp.prototype[@@replace]()")}}</dt> + <dd>Replaces matches in given string with new substring.</dd> + <dt>{{JSxRef("RegExp.prototype.@@search()", "RegExp.prototype[@@search]()")}}</dt> + <dd>Searches the match in given string and returns the index the pattern found in the string.</dd> + <dt>{{JSxRef("RegExp.prototype.@@split()", "RegExp.prototype[@@split]()")}}</dt> + <dd>Splits given string into an array by separating the string into substring.</dd> + <dt>{{JSxRef("RegExp.prototype.toSource()")}}</dt> + <dd>Returns an object literal representing the specified object; you can use this value to create a new object. Overrides the {{JSxRef("Object.prototype.toSource()")}} method.</dd> + <dt>{{JSxRef("RegExp.prototype.toString()")}}</dt> + <dd>Returns a string representing the specified object. Overrides the {{JSxRef("Object.prototype.toString()")}} method.</dd> +</dl> +</div> + +<h2 id="Examples">Examples</h2> + +<h3 id="Using_a_regular_expression_to_change_data_format">Using a regular expression to change data format</h3> + +<p>The following script uses the {{jsxref("String.prototype.replace()", "replace()")}} method of the {{jsxref("Global_Objects/String", "String")}} instance to match a name in the format <em>first last</em> and output it in the format <em>last, first</em>.</p> + +<p>In the replacement text, the script uses <code>$1</code> and <code>$2</code> to indicate the results of the corresponding matching parentheses in the regular expression pattern.</p> + +<pre class="brush: js">let re = /(\w+)\s(\w+)/ +let str = 'John Smith' +let newstr = str.replace(re, '$2, $1') +console.log(newstr) +</pre> + +<p>This displays <code>"Smith, John"</code>.</p> + +<h3 id="Using_regular_expression_to_split_lines_with_different_line_endingsends_of_lineline_breaks">Using regular expression to split lines with different <strong>line endings/ends of line/line breaks</strong></h3> + +<p>The default line ending varies depending on the platform (Unix, Windows, etc.). The line splitting provided in this example works on all platforms.</p> + +<pre class="brush: js">let text = 'Some text\nAnd some more\r\nAnd yet\rThis is the end' +let lines = text.split(/\r\n|\r|\n/) +console.log(lines) // logs [ 'Some text', 'And some more', 'And yet', 'This is the end' ] +</pre> + +<p>Note that the order of the patterns in the regular expression matters.</p> + +<h3 id="Using_regular_expression_on_multiple_lines">Using regular expression on multiple lines</h3> + +<pre class="brush: js">let s = 'Please yes\nmake my day!' + +s.match(/yes.*day/); +// Returns null + +s.match(/yes[^]*day/); +// Returns ["yes\nmake my day"] +</pre> + +<h3 id="Using_a_regular_expression_with_the_sticky_flag">Using a regular expression with the sticky flag</h3> + +<p>The <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/sticky">sticky flag</a> indicates that the regular expression performs sticky matching in the target string by attempting to match starting at {{jsxref("RegExp.prototype.lastIndex")}}.</p> + +<pre class="brush: js">let str = '#foo#' +let regex = /foo/y + +regex.lastIndex = 1 +regex.test(str) // true +regex.lastIndex = 5 +regex.test(str) // false (lastIndex is taken into account with sticky flag) +regex.lastIndex // 0 (reset after match failure)</pre> + +<h3 id="The_difference_between_the_sticky_flag_and_the_global_flag">The difference between the sticky flag and the global flag</h3> + +<p>With the sticky flag y, the next match has to happen at the lastIndex position, while with the global flag g, the match can happen at the lastIndex position or later:</p> + +<pre class="brush: js">re = /\d/y; +while (r = re.exec("123 456")) console.log(r, "AND re.lastIndex", re.lastIndex); + +// [ '1', index: 0, input: '123 456', groups: undefined ] AND re.lastIndex 1 +// [ '2', index: 1, input: '123 456', groups: undefined ] AND re.lastIndex 2 +// [ '3', index: 2, input: '123 456', groups: undefined ] AND re.lastIndex 3 +// ... and no more match.</pre> + +<p>With the global flag g, all 6 digits would be matched, not just 3.</p> + +<h3 id="Regular_expression_and_Unicode_characters">Regular expression and Unicode characters</h3> + +<p>As mentioned above, <code>\w</code> or <code>\W</code> only matches ASCII based characters; for example, <code>a</code> to <code>z</code>, <code>A</code> to <code>Z</code>, <code>0</code> to <code>9</code>, and <code>_</code>.</p> + +<p>To match characters from other languages such as Cyrillic or Hebrew, use <code>\u<var>hhhh</var></code>, where <code><var>hhhh</var></code> is the character's Unicode value in hexadecimal.</p> + +<p>This example demonstrates how one can separate out Unicode characters from a word.</p> + +<pre class="brush: js">let text = 'Образец text на русском языке' +let regex = /[\u0400-\u04FF]+/g + +let match = regex.exec(text) +console.log(match[0]) // logs 'Образец' +console.log(regex.lastIndex) // logs '7' + +let match2 = regex.exec(text) +console.log(match2[0]) // logs 'на' [did not log 'text'] +console.log(regex.lastIndex) // logs '15' + +// and so on +</pre> + +<p>The <a href="/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Unicode_Property_Escapes">Unicode property escapes</a> feature introduces a solution, by allowing for a statement as simple as <code>\p{scx=Cyrl}</code>. One can also use an external resource for getting the complete Unicode block range for different scripts, such as <a href="http://kourge.net/projects/regexp-unicode-block">Regexp-Unicode-block</a>.</p> + +<h3 id="Extracting_sub-domain_name_from_URL">Extracting sub-domain name from URL</h3> + +<pre class="brush: js">let url = 'http://xxx.domain.com' +console.log(/[^.]+/.exec(url)[0].substr(7)) // logs 'xxx' +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-regexp-regular-expression-objects', 'RegExp')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("javascript.builtins.RegExp")}}</p> +</div> + +<h3 id="Firefox-specific_notes">Firefox-specific notes</h3> + +<p>Starting with Firefox 34, in the case of a capturing group with quantifiers preventing its exercise, the matched text for a capturing group is now <code>undefined</code> instead of an empty string:</p> + +<pre class="brush: js">// Firefox 33 or older +'x'.replace(/x(.)?/g, function(m, group) { + console.log("'group:" + group + "'"); +}); +// 'group:' + +// Firefox 34 or newer +'x'.replace(/x(.)?/g, function(m, group) { + console.log("'group:" + group + "'"); +}); +// 'group:undefined' +</pre> + +<p>Note that due to web compatibility, <code>RegExp.$N</code> will still return an empty string instead of <code>undefined</code> (<a href="https://bugzilla.mozilla.org/show_bug.cgi?id=1053944">bug 1053944</a>).</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Guide/Regular_Expressions">Regular Expressions</a> chapter in the <a href="/en-US/docs/Web/JavaScript/Guide">JavaScript Guide</a></li> + <li>{{jsxref("String.prototype.match()")}}</li> + <li>{{jsxref("String.prototype.replace()")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/set/add/index.html b/files/zh-tw/web/javascript/reference/global_objects/set/add/index.html new file mode 100644 index 0000000000..b0a85a0a06 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/set/add/index.html @@ -0,0 +1,83 @@ +--- +title: Set.prototype.add() +slug: Web/JavaScript/Reference/Global_Objects/Set/add +tags: + - ECMAScript 2015 + - JavaScript + - 原型 + - 參考 + - 方法 + - 集合 +translation_of: Web/JavaScript/Reference/Global_Objects/Set/add +--- +<div>{{JSRef}}</div> + +<p><code><strong>add()</strong></code> 會在一個 <code>Set</code> 物件的尾端加上一個指定 <code>value</code> 的新元素。</p> + +<div>{{EmbedInteractiveExample("pages/js/set-prototype-add.html")}}</div> + + + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox"><em>mySet</em>.add(<em>value</em>);</pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>value</code></dt> + <dd>要被加到 <code>Set</code> 物件中的值。</dd> +</dl> + +<h3 id="回傳值">回傳值</h3> + +<p><code>Set</code> 物件本身。</p> + +<h2 id="範例">範例</h2> + +<h3 id="使用_add_方法">使用 <code>add</code> 方法</h3> + +<pre class="brush: js">var mySet = new Set(); + +mySet.add(1); +mySet.add(5).add('some text'); // chainable + +console.log(mySet); +// Set [1, 5, "some text"] +</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('ES2015', '#sec-set.prototype.add', 'Set.prototype.add')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-set.prototype.add', 'Set.prototype.add')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + + + +<p>{{Compat("javascript.builtins.Set.add")}}</p> + +<h2 id="另見">另見</h2> + +<ul> + <li>{{jsxref("Set")}}</li> + <li>{{jsxref("Set.prototype.delete()")}}</li> + <li>{{jsxref("Set.prototype.has()")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/set/clear/index.html b/files/zh-tw/web/javascript/reference/global_objects/set/clear/index.html new file mode 100644 index 0000000000..2eb8875c34 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/set/clear/index.html @@ -0,0 +1,79 @@ +--- +title: Set.prototype.clear() +slug: Web/JavaScript/Reference/Global_Objects/Set/clear +tags: + - ECMAScript 2015 + - JavaScript + - 原型 + - 參考 + - 方法 + - 集合 +translation_of: Web/JavaScript/Reference/Global_Objects/Set/clear +--- +<div>{{JSRef}}</div> + +<p><code><strong>clear()</strong></code> 方法會從一個 <code>Set</code> 物件中移除其所有元素。</p> + +<div>{{EmbedInteractiveExample("pages/js/set-prototype-clear.html")}}</div> + + + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox"><em>mySet</em>.clear();</pre> + +<h3 id="回傳值">回傳值</h3> + +<p>{{jsxref("undefined")}}.</p> + +<h2 id="範例">範例</h2> + +<h3 id="使用_clear_方法">使用 <code>clear</code> 方法</h3> + +<pre class="brush: js">var mySet = new Set(); +mySet.add(1); +mySet.add('foo'); + +mySet.size; // 2 +mySet.has('foo'); // true + +mySet.clear(); + +mySet.size; // 0 +mySet.has('bar') // false +</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('ES2015', '#sec-set.prototype.clear', 'Set.prototype.clear')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-set.prototype.clear', 'Set.prototype.clear')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + + + +<p>{{Compat("javascript.builtins.Set.clear")}}</p> + +<h2 id="另見">另見</h2> + +<ul> + <li>{{jsxref("Set")}}</li> + <li>{{jsxref("Set.prototype.delete()")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/set/delete/index.html b/files/zh-tw/web/javascript/reference/global_objects/set/delete/index.html new file mode 100644 index 0000000000..d465f45bef --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/set/delete/index.html @@ -0,0 +1,98 @@ +--- +title: Set.prototype.delete() +slug: Web/JavaScript/Reference/Global_Objects/Set/delete +tags: + - ECMAScript 2015 + - JavaScript + - 原型 + - 參考 + - 方法 + - 集合 +translation_of: Web/JavaScript/Reference/Global_Objects/Set/delete +--- +<div>{{JSRef}}</div> + +<p><code><strong>delete()</strong></code> 方法會一個 <code>Set</code> 物件中移除指定元素。</p> + +<div>{{EmbedInteractiveExample("pages/js/set-prototype-delete.html")}}</div> + + + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox"><em>mySet</em>.delete(<em>value</em>);</pre> + +<h3 id="參數'">參數'</h3> + +<dl> + <dt><code>value</code></dt> + <dd>要從 <code>Set</code> 物件中移除的值。</dd> +</dl> + +<h3 id="回傳值">回傳值</h3> + +<p><code>true</code> 如果成功從 <code>Set</code> 物件中移除;反之 <code>false</code>。</p> + +<h2 id="範例">範例</h2> + +<h3 id="使用_delete_方法">使用 <code>delete</code> 方法</h3> + +<pre class="brush: js">var mySet = new Set(); +mySet.add('foo'); + +mySet.delete('bar'); // Returns false. No "bar" element found to be deleted. +mySet.delete('foo'); // Returns true. Successfully removed. + +mySet.has('foo'); // Returns false. The "foo" element is no longer present. +</pre> + +<p>下方展示了如何從一個 Set 中移除物件。</p> + +<pre class="brush: js">var setObj = new Set(); // Create a New Set. + +setObj.add({x: 10, y: 20}); // Add object in the set. + +setObj.add({x: 20, y: 30}); // Add object in the set. + +// Delete any point with `x > 10`. +setObj.forEach(function(point){ + if(point.x > 10){ + setObj.delete(point) + } +}) +</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('ES2015', '#sec-set.prototype.delete', 'Set.prototype.delete')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-set.prototype.delete', 'Set.prototype.delete')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + + + +<p>{{Compat("javascript.builtins.Set.delete")}}</p> + +<h2 id="另見">另見</h2> + +<ul> + <li>{{jsxref("Set")}}</li> + <li>{{jsxref("Set.prototype.clear()")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/set/entries/index.html b/files/zh-tw/web/javascript/reference/global_objects/set/entries/index.html new file mode 100644 index 0000000000..6bf609afb2 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/set/entries/index.html @@ -0,0 +1,78 @@ +--- +title: Set.prototype.entries() +slug: Web/JavaScript/Reference/Global_Objects/Set/entries +tags: + - ECMAScript 2015 + - JavaScript + - 原型 + - 方法 + - 迭代器 + - 集合 +translation_of: Web/JavaScript/Reference/Global_Objects/Set/entries +--- +<div>{{JSRef}}</div> + +<div><code><strong>entries()</strong></code> 方法回傳一個 <code>Iterator</code> 物件,其包含著一個由插入順序排序,<code>Set</code> 物件中每個元素的<strong> <code>[value, value]</code></strong> 陣列。儘管對 <code>Set</code> 物件來說沒有像 <code>Map</code> 一樣的 <code>key</code> 概念,為了確保這個 API 運作的與 <code>Map</code> 相似,每個 <em>entry</em> 都有同樣的值同時作為其 <em>key</em> 和 <em>value</em> ,因此回傳的是一個<strong><code>[value, value]</code></strong> 的陣列。</div> + +<div>{{EmbedInteractiveExample("pages/js/set-prototype-entries.html")}}</div> + + + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox"><code><em>mySet</em>.entries()</code></pre> + +<h3 id="回傳值">回傳值</h3> + +<p>一個新的 <code>Iterator</code> 物件,包含著一個由插入順序排序,<code>Set</code> 物件中每個元素的<strong> <code>[value, value]</code></strong> 陣列。</p> + +<h2 id="範例">範例</h2> + +<h3 id="使用_entries()">使用 <code>entries()</code></h3> + +<pre class="brush:js">var mySet = new Set(); +mySet.add('foobar'); +mySet.add(1); +mySet.add('baz'); + +var setIter = mySet.entries(); + +console.log(setIter.next().value); // ["foobar", "foobar"] +console.log(setIter.next().value); // [1, 1] +console.log(setIter.next().value); // ["baz", "baz"] +</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('ES2015', '#sec-set.prototype.entries', 'Set.prototype.entries')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-set.prototype.entries', 'Set.prototype.entries')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + + + +<p>{{Compat("javascript.builtins.Set.entries")}}</p> + +<h2 id="另見">另見</h2> + +<ul> + <li>{{jsxref("Set.prototype.keys()")}}</li> + <li>{{jsxref("Set.prototype.values()")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/set/has/index.html b/files/zh-tw/web/javascript/reference/global_objects/set/has/index.html new file mode 100644 index 0000000000..c77d2ea99b --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/set/has/index.html @@ -0,0 +1,92 @@ +--- +title: Set.prototype.has() +slug: Web/JavaScript/Reference/Global_Objects/Set/has +tags: + - ECMAScript 2015 + - JavaScript + - 原型 + - 方法 + - 集合 +translation_of: Web/JavaScript/Reference/Global_Objects/Set/has +--- +<div>{{JSRef}}</div> + +<p><code><strong>has()</strong></code> 方法對一個指定值元素在 <code>Set</code> 物件中的存在與否回傳一個布林值。</p> + +<div>{{EmbedInteractiveExample("pages/js/set-prototype-has.html")}}</div> + + + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox"><em>mySet</em>.has(<em>value</em>);</pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>value</code></dt> + <dd>要測試是否存在在 <code>Set</code> 中的值。</dd> +</dl> + +<h3 id="回傳值">回傳值</h3> + +<p>回傳 <code>true</code> 如果給定值存在在 <code>Set</code> 物件中;反之回傳 <code>false</code> 。</p> + +<div class="blockIndicator note"> +<p><strong>Note:</strong> 技術上來說,<code>has()</code> 使用了 <code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness#Same-value-zero_equality">sameValueZero</a></code> 算法來判斷給定元素的存在與否。</p> +</div> + +<h2 id="範例">範例</h2> + +<h3 id="使用_has_方法">使用 <code>has</code> 方法</h3> + +<pre class="brush: js">var mySet = new Set(); +mySet.add('foo'); + +mySet.has('foo'); // returns true +mySet.has('bar'); // returns false + +var set1 = new Set(); +var obj1 = {'key1': 1}; +set1.add(obj1); + +set1.has(obj1); // returns true +set1.has({'key1': 1}); // returns false because they are different object references +set1.add({'key1': 1}); // now set1 contains 2 entries +</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('ES2015', '#sec-set.prototype.has', 'Set.prototype.has')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-set.prototype.has', 'Set.prototype.has')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + + + +<p>{{Compat("javascript.builtins.Set.has")}}</p> + +<h2 id="另見">另見</h2> + +<ul> + <li>{{jsxref("Set")}}</li> + <li>{{jsxref("Set.prototype.add()")}}</li> + <li>{{jsxref("Set.prototype.delete()")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/set/index.html b/files/zh-tw/web/javascript/reference/global_objects/set/index.html new file mode 100644 index 0000000000..2b3f80fdd1 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/set/index.html @@ -0,0 +1,243 @@ +--- +title: Set +slug: Web/JavaScript/Reference/Global_Objects/Set +tags: + - ECMAScript 2015 + - Global Objects + - JavaScript + - Object + - set +translation_of: Web/JavaScript/Reference/Global_Objects/Set +--- +<div>{{JSRef}}</div> + +<p><strong><code>Set</code></strong> 物件可讓你儲存任何類型的唯一值(unique),不論是{{Glossary("Primitive", "基本型別(primitive)值")}}或物件參考(references)。</p> + +<div>{{EmbedInteractiveExample("pages/js/set-prototype-constructor.html")}}</div> + + + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox notranslate">new Set([<em>iterable</em>]);</pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>iterable</code></dt> + <dd>若一個<a href="/zh-TW/docs/Web/JavaScript/Reference/Statements/for...of">可迭代物件</a>被傳入,其所有的元素將會被加入至新的 <code>Set</code>。若你沒有指定此參數,或參數值為 <code>null</code>,則新的 <code>Set</code> 會是空的。</dd> +</dl> + +<h3 id="回傳值">回傳值</h3> + +<p>一個新的 <code>Set</code> 物件。</p> + +<h2 id="描述">描述</h2> + +<p><code>Set</code> 對象是數值的收集器。您可以按插入順序迭代收集器中的元素。在 <code>Set</code> 裡的元素只會出現一次<strong>;</strong> 意即在<code>Set</code>裡的元素都是獨一無二</p> + +<h3 id="值的相等性">值的相等性</h3> + +<p>因為在 Set 裡每個值都是獨立的,所以都會檢查值的相等性。在早期的ECMAScript規範版本中,此處算法跟基於===操作符中使用的算法並不相同。具體來說,在 <code>Set</code>裡+0(在嚴格模式是和-0相等)和-0是不同的值。然而在 ECMAScript 2015規範中這點已被更改。請參閱 <a href="#Browser_compatibility">瀏覽器兼容性</a> 中的"Value equality for -0 and 0"。</p> + +<p>另外,NaN和undefined都可以被放置在Set 中, NaN之間被視為相同的值(儘管 NaN !== NaN)。</p> + +<dl> + <dt><code>Set.length</code></dt> + <dd>The value of the <code>length</code> property is 0.</dd> + <dt>{{jsxref("Set.@@species", "get Set[@@species]")}}</dt> + <dd>The constructor function that is used to create derived objects.</dd> + <dt>{{jsxref("Set.prototype")}}</dt> + <dd>Represents the prototype for the <code>Set</code> constructor. Allows the addition of properties to all <code>Set</code> objects.</dd> +</dl> + +<h2 id="Set_物件實體"><code>Set</code> 物件實體</h2> + +<p>All <code>Set</code> instances inherit from {{jsxref("Set.prototype")}}.</p> + +<h3 id="屬性">屬性</h3> + +<p>{{page('en-US/Web/JavaScript/Reference/Global_Objects/Set/prototype','Properties')}}</p> + +<h3 id="方法">方法</h3> + +<p>{{page('en-US/Web/JavaScript/Reference/Global_Objects/Set/prototype','Methods')}}</p> + +<h2 id="範例">範例</h2> + +<h3 id="使用_Set_物件">使用 <code>Set</code> 物件</h3> + +<pre class="brush: js notranslate">var mySet = new Set(); + +mySet.add(1); // Set [ 1 ] +mySet.add(5); // Set [ 1, 5 ] +mySet.add(5); // Set [ 1, 5 ] +mySet.add('some text'); // Set [ 1, 5, 'some text' ] +var o = {a: 1, b: 2}; +mySet.add(o); + +mySet.add({a: 1, b: 2}); // o is referencing a different object so this is okay + +mySet.has(1); // true +mySet.has(3); // false, 3 has not been added to the set +mySet.has(5); // true +mySet.has(Math.sqrt(25)); // true +mySet.has('Some Text'.toLowerCase()); // true +mySet.has(o); // true + +mySet.size; // 5 + +mySet.delete(5); // removes 5 from the set +mySet.has(5); // false, 5 has been removed + +mySet.size; // 4, we just removed one value +console.log(mySet);// Set [ 1, "some text", Object {a: 1, b: 2}, Object {a: 1, b: 2} ]</pre> + +<h3 id="迭代_Sets">迭代 Sets</h3> + +<pre class="brush: js notranslate">// iterate over items in set +// logs the items in the order: 1, "some text", {"a": 1, "b": 2}, {"a": 1, "b": 2} +for (let item of mySet) console.log(item); + +// logs the items in the order: 1, "some text", {"a": 1, "b": 2}, {"a": 1, "b": 2} +for (let item of mySet.keys()) console.log(item); + +// logs the items in the order: 1, "some text", {"a": 1, "b": 2}, {"a": 1, "b": 2} +for (let item of mySet.values()) console.log(item); + +// logs the items in the order: 1, "some text", {"a": 1, "b": 2}, {"a": 1, "b": 2} +//(key and value are the same here) +for (let [key, value] of mySet.entries()) console.log(key); + +// convert Set object to an Array object, with <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from">Array.from</a> +var myArr = Array.from(mySet); // [1, "some text", {"a": 1, "b": 2}, {"a": 1, "b": 2}] + +// the following will also work if run in an HTML document +mySet.add(document.body); +mySet.has(document.querySelector('body')); // true + +// converting between Set and Array +mySet2 = new Set([1, 2, 3, 4]); +mySet2.size; // 4 +[...mySet2]; // [1, 2, 3, 4] + +// intersect can be simulated via +var intersection = new Set([...set1].filter(x => set2.has(x))); + +// difference can be simulated via +var difference = new Set([...set1].filter(x => !set2.has(x))); + +// Iterate set entries with forEach +mySet.forEach(function(value) { + console.log(value); +}); + +// 1 +// 2 +// 3 +// 4</pre> + +<h3 id="實作基本的_set_操作">實作基本的 set 操作</h3> + +<pre class="brush: js notranslate">Set.prototype.isSuperset = function(subset) { + for (var elem of subset) { + if (!this.has(elem)) { + return false; + } + } + return true; +} + +Set.prototype.union = function(setB) { + var union = new Set(this); + for (var elem of setB) { + union.add(elem); + } + return union; +} + +Set.prototype.intersection = function(setB) { + var intersection = new Set(); + for (var elem of setB) { + if (this.has(elem)) { + intersection.add(elem); + } + } + return intersection; +} + +Set.prototype.difference = function(setB) { + var difference = new Set(this); + for (var elem of setB) { + difference.delete(elem); + } + return difference; +} + +//Examples +var setA = new Set([1, 2, 3, 4]), + setB = new Set([2, 3]), + setC = new Set([3, 4, 5, 6]); + +setA.isSuperset(setB); // => true +setA.union(setC); // => Set [1, 2, 3, 4, 5, 6] +setA.intersection(setC); // => Set [3, 4] +setA.difference(setC); // => Set [1, 2] + +</pre> + +<h3 id="與_Array_物件關聯">與 <code>Array</code> 物件關聯</h3> + +<pre class="brush: js notranslate">var myArray = ['value1', 'value2', 'value3']; + +// Use the regular Set constructor to transform an Array into a Set +var mySet = new Set(myArray); + +mySet.has('value1'); // returns true + +// Use the spread operator to transform a set into an Array. +console.log([...mySet]); // Will show you exactly the same Array as myArray</pre> + +<h3 id="與_Strings_關聯">與 <code>Strings</code> 關聯</h3> + +<pre class="brush: js notranslate">var text = 'India'; + +var mySet = new Set(text); // Set ['I', 'n', 'd', 'i', 'a'] +mySet.size; // 5 +</pre> + +<h2 id="規範">規範</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-set-objects', 'Set')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-set-objects', 'Set')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + + + +<p>{{Compat("javascript.builtins.Set")}}</p> + +<h2 id="參見">參見</h2> + +<ul> + <li>{{jsxref("Map")}}</li> + <li>{{jsxref("WeakMap")}}</li> + <li>{{jsxref("WeakSet")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/set/values/index.html b/files/zh-tw/web/javascript/reference/global_objects/set/values/index.html new file mode 100644 index 0000000000..bb136ba806 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/set/values/index.html @@ -0,0 +1,79 @@ +--- +title: Set.prototype.values() +slug: Web/JavaScript/Reference/Global_Objects/Set/values +tags: + - ECMAScript 2015 + - JavaScript + - 原型 + - 方法 + - 迭代器 + - 集合 +translation_of: Web/JavaScript/Reference/Global_Objects/Set/values +--- +<div>{{JSRef}}</div> + +<p><code><strong>values()</strong></code> 方法回傳一個 <code>Iterator</code> 物件,包含著 <code>Set</code> 物件中所有元素,由插入順序排序。</p> + +<p><strong><code>keys()</code></strong> 是這個方法的替身 (為了與 {{jsxref("Map")}} 物件保持相似性);他運行的完全一模一樣,回傳 <code>Set</code> 中元素的 <strong>values</strong> 。</p> + +<div>{{EmbedInteractiveExample("pages/js/set-prototype-values.html")}}</div> + + + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox"><code><em>mySet</em>.values(); +</code></pre> + +<h3 id="回傳值">回傳值</h3> + +<p>一個 <code>Iterator</code> 物件,包含著 <code>Set</code> 物件中所有元素,由插入順序排序。</p> + +<h2 id="範例">範例</h2> + +<h3 id="使用_values()">使用 <code>values()</code></h3> + +<pre class="brush:js">var mySet = new Set(); +mySet.add('foo'); +mySet.add('bar'); +mySet.add('baz'); + +var setIter = mySet.values(); + +console.log(setIter.next().value); // "foo" +console.log(setIter.next().value); // "bar" +console.log(setIter.next().value); // "baz"</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('ES2015', '#sec-set.prototype.values', 'Set.prototype.values')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-set.prototype.values', 'Set.prototype.values')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + + + +<p>{{Compat("javascript.builtins.Set.values")}}</p> + +<h2 id="另見">另見</h2> + +<ul> + <li>{{jsxref("Set.prototype.entries()")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/string/index.html b/files/zh-tw/web/javascript/reference/global_objects/string/index.html new file mode 100644 index 0000000000..ad4474693a --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/string/index.html @@ -0,0 +1,328 @@ +--- +title: 字串 +slug: Web/JavaScript/Reference/Global_Objects/String +tags: + - ECMAScript 2015 + - JavaScript + - Reference + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String +--- +<p>{{JSRef("Global_Objects", "String")}}</p> + +<p><strong><code>String</code></strong> 全域物件為字串的構造函數,或是一個字符序列。</p> + +<h2 id="Syntax" name="Syntax">語法</h2> + +<p>字串文字採用下列形式:</p> + +<pre>'string text' "string text" "中文 español deutsch English हिन्दी العربية português বাংলা русский 日本語 ਪੰਜਾਬੀ 한국어 தமிழ் עברית"</pre> + +<p>字串也可以被全域的 <code>String</code> 物件建立:</p> + +<pre>String(thing)</pre> + +<h3 id="Parameters" name="Parameters">參數</h3> + +<dl> + <dt><code>thing</code></dt> + <dd>任何要轉換成字串的物件。</dd> +</dl> + +<h3 id="樣板字面值">樣板字面值</h3> + +<p>自 ECMAScript 2015,字串文字也可以是<a href="https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Template_literals">樣板字面值(Template literals)</a>:</p> + +<pre>`hello world` `hello! world!` `hello ${who}` escape `<a>${who}</a>`</pre> + +<h3 id="跳脫符號">跳脫符號</h3> + +<p>除了常規的、可印出來的字元,特殊字元也可以被跳脫符號來表示編碼。</p> + +<table> + <thead> + <tr> + <th scope="col">代碼</th> + <th scope="col">輸出</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>\0</code></td> + <td>空字元</td> + </tr> + <tr> + <td><code>\'</code></td> + <td>單引號</td> + </tr> + <tr> + <td><code>\"</code></td> + <td>雙引號</td> + </tr> + <tr> + <td><code>\\</code></td> + <td>反斜線</td> + </tr> + <tr> + <td><code>\n</code></td> + <td>斷行</td> + </tr> + <tr> + <td><code>\r</code></td> + <td>回車</td> + </tr> + <tr> + <td><code>\v</code></td> + <td>垂直制表</td> + </tr> + <tr> + <td><code>\t</code></td> + <td>制表</td> + </tr> + <tr> + <td><code>\b</code></td> + <td>退格</td> + </tr> + <tr> + <td><code>\f</code></td> + <td>饋頁</td> + </tr> + <tr> + <td><code>\uXXXX</code></td> + <td>unicode 代碼</td> + </tr> + <tr> + <td><code>\u{X}</code> ... <code>\u{XXXXXX}</code></td> + <td>unicode 代碼 {{experimental_inline}}</td> + </tr> + <tr> + <td><code>\xXX</code></td> + <td>Latin-1 字元</td> + </tr> + </tbody> +</table> + +<dl> +</dl> + +<div class="note"> +<p>和其他語言不同,JavaScript 將單引號字串和雙引號字串是做相同;因此,上述的序列可以在單引號或雙引號中作用。</p> +</div> + +<dl> +</dl> + +<h3 id="長字面值字串">長字面值字串</h3> + +<p>有些時候,你的程式碼會包含非常長的字串。 為了不讓長字串無止盡地往下長,抑或是在你心血來潮的時候,你可能希望將這樣長的字串能夠斷成多行卻不影響到實際的內容。</p> + +<p>你可以用 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Addition_()">+</a> 運算子附加多個字串在一起,像是這樣:</p> + +<pre><code>let longString = "This is a very long string which needs " + + "to wrap across multiple lines because " + + "otherwise my code is unreadable.";</code></pre> + +<p>或者,你可以在每一行尾端用反斜線字元("\")表示字串會繼續被顯示在下一列。 你必須要確定在反斜線後面沒有任何空白或其他字元,甚至是縮排;否則這個方法將失效。 這個形式看起來像這樣:</p> + +<pre><code>let longString = "This is a very long string which needs \ +to wrap across multiple lines because \ +otherwise my code is unreadable.";</code></pre> + +<p>這兩個方法都會建立相同的字串內容。</p> + +<h2 id="Description" name="Description">說明</h2> + +<p>字串對於能保留以文字形式表達的資料這件事來說,是有用的。在字串上,一些最常被使用的運算即確認字串長度 {{jsxref("String.length", "length")}} ,用 <a href="/en-US/docs/Web/JavaScript/Reference/Operators/String_Operators">+ 或 += 字串運算元</a> 建造或者串接字串,用 {{jsxref("String.indexOf", "indexOf")}} 方法檢查?子字串是否存在或子字串的位置,或者是用 {{jsxref("String.substring", "substring")}} 方法將子字串抽取出來。</p> + +<h3 id="Character_access" name="Character_access">存取字元</h3> + +<p>有兩個方法可以存取字串中個別的字元。第一個是用 {{jsxref("String.charAt", "charAt")}} 方法:</p> + +<pre class="brush: js">return 'cat'.charAt(1); // 回傳 "a" +</pre> + +<p>另一個(在ECMAScript 5中被提到)方法是將字串當作一個類似陣列的物件,直接存取字串中對應的數值索引。</p> + +<pre class="brush: js">return 'cat'[1]; // 回傳 "a" +</pre> + +<p>對於存取字元使用的括號表達式,沒辦法去刪除或指派一個值給這些屬性。 這些屬性既非可寫的,也非可設定的。(參見 {{jsxref("Object.defineProperty")}})</p> + +<h3 id="Comparing_strings" name="Comparing_strings">比較字串</h3> + +<p>C 語言的開發者有 <code>strcmp()</code> 函式可以用來比較字串。 在 JavaScript 中,你只能用<a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators">小於和大於運算子</a>:</p> + +<pre class="brush: js">var a = "a"; +var b = "b"; +if (a < b) // true + print(a + " 小於 " + b); +else if (a > b) + print(a + " 大於 " + b); +else + print(a + " 和 " + b + " 相等"); +</pre> + +<p>這樣類似的結果,也能使用繼承 <code>String</code> 實體的 {{jsxref("String.localeCompare", "localeCompare")}} 方法來實現。</p> + +<h3 id="分辨_string_原始型別和_String_物件">分辨 string 原始型別和 <code>String</code> 物件</h3> + +<p>請注意,JavaScript 會區別 <code>String</code> 物件和原始字串({{jsxref("Global_Objects/Boolean", "Boolean")}} 和 {{jsxref("Global_Objects/Number", "Numbers")}} 也是如此)。</p> + +<p>String literals (denoted by double or single quotes) and strings returned from <code>String</code> calls in a non-constructor context (i.e., without using the <a href="/en-US/docs/Web/JavaScript/Reference/Operators/new"><code>new</code> keyword</a>) are primitive strings. JavaScript automatically converts primitives to <code>String</code> objects, so that it's possible to use <code>String</code> object methods for primitive strings. In contexts where a method is to be invoked on a primitive string or a property lookup occurs, JavaScript will automatically wrap the string primitive and call the method or perform the property lookup.</p> + +<pre class="brush: js">var s_prim = "foo"; +var s_obj = new String(s_prim); + +console.log(typeof s_prim); // 印出 "string" +console.log(typeof s_obj); // 印出 "object" +</pre> + +<p>字串原始型別和 <code>String</code> 物件也會在使用 {{jsxref("Global_Objects/eval", "eval")}} 時給出不同的結果。 原始型別傳進 <code>eval</code> 會被視為原始代碼;<code>String</code> 物件則會回傳,且被視作是其他物件。舉個例子:</p> + +<pre class="brush: js">s1 = "2 + 2"; // 建立一個字串原始型別 +s2 = new String("2 + 2"); // 建立一個字串物件 +console.log(eval(s1)); // 回傳數字 4 +console.log(eval(s2)); // 回傳字串 "2 + 2" +</pre> + +<p>因為一些原因,程式碼也許在遇到 <code>String</code> 物件時,但需要的卻是字串原始型別;儘管如此,通常作者們不需要擔心它的差異。</p> + +<p>一個 <code>String</code> 物件總能夠使用 {{jsxref("String.valueOf", "valueOf")}} 方法被轉換成自身的原始副本。</p> + +<pre class="brush: js">console.log(eval(s2.valueOf())); // 回傳數字 4 +</pre> + +<div class="note"><strong>注意:</strong> 對於在 JavaScript 中其他可用的字串方法,請參閱這篇文章<a href="/en-US/docs/Web/JavaScript/Typed_arrays/StringView" title="/en-US/docs/Web/JavaScript/Typed_arrays/StringView"><code>StringView</code> – a C-like representation of strings based on typed arrays</a>。</div> + +<h2 id="Properties" name="Properties">屬性</h2> + +<dl> + <dt>{{jsxref("String.prototype")}}</dt> + <dd>能讓字串物件增加屬性。</dd> +</dl> + +<div>{{jsOverrides("Function", "Properties", "prototype")}}</div> + +<h2 id="Methods" name="Methods">方法</h2> + +<dl> + <dt>{{jsxref("String.fromCharCode()")}}</dt> + <dd>利用 Unicode 值的序列建立並回傳一個字串。</dd> + <dt>{{jsxref("String.fromCodePoint()")}} {{experimental_inline}}</dt> + <dd>利用編碼位置的序列建立並回傳一個字串。</dd> +</dl> + +<div>{{jsOverrides("Function", "Methods", "fromCharCode", "fromCodePoint")}}</div> + +<h2 id="String_通用方法"><code>String</code> 通用方法</h2> + +<div class="warning"> +<p>字串通用方法是非標準化的、被棄用的,也有近期將被刪除的。</p> +</div> + +<p>The <code>String </code>instance methods are also available in Firefox as of JavaScript 1.6 (though not part of the ECMAScript standard) on the String object for applying String methods to any object:</p> + +<pre class="brush: js">var num = 15; +alert(String.replace(num, /5/, '2')); +</pre> + +<p class="brush: js"><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#Array_generic_methods">Generics</a> are also available on {{jsxref("Global_Objects/Array", "Array")}} methods.</p> + +<p class="brush: js">The following is a shim to provide support to non-supporting browsers:</p> + +<pre class="brush: js">/*globals define*/ +// Assumes all supplied String instance methods already present +// (one may use shims for these if not available) +(function () { + 'use strict'; + + var i, + // We could also build the array of methods with the following, but the + // getOwnPropertyNames() method is non-shimable: + // Object.getOwnPropertyNames(String).filter(function (methodName) + // {return typeof String[methodName] === 'function'}); + methods = [ + 'quote', 'substring', 'toLowerCase', 'toUpperCase', 'charAt', + 'charCodeAt', 'indexOf', 'lastIndexOf', 'startsWith', 'endsWith', + 'trim', 'trimLeft', 'trimRight', 'toLocaleLowerCase', + 'toLocaleUpperCase', 'localeCompare', 'match', 'search', + 'replace', 'split', 'substr', 'concat', 'slice' + ], + methodCount = methods.length, + assignStringGeneric = function (methodName) { + var method = String.prototype[methodName]; + String[methodName] = function (arg1) { + return method.apply(arg1, Array.prototype.slice.call(arguments, 1)); + }; + }; + + for (i = 0; i < methodCount; i++) { + assignStringGeneric(methods[i]); + } +}());</pre> + +<h2 id="String_instances" name="String_instances"><code>String</code> instances</h2> + +<h3 id="Properties_2">Properties</h3> + +<p>{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Properties')}}</p> + +<p>{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Methods')}}</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="String_conversion">String conversion</h3> + +<p>It's possible to use <code>String</code> as a "safer" {{jsxref("String.toString", "toString")}} alternative, as although it still normally calls the underlying <code>toString</code>, it also works for <code>null</code> and <code>undefined</code>. For example:</p> + +<pre class="brush: js">var outputStrings = []; +for (let i = 0, n = inputValues.length; i < n; ++i) { + outputStrings.push(String(inputValues[i])); +} +</pre> + +<h2 id="規範">規範</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5', 'String')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-string-objects', 'String')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string-objects', 'String')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.String.String")}}</p> + +<h2 id="參見">參見</h2> + +<ul> + <li>{{domxref("DOMString")}}</li> + <li><a href="/en-US/Add-ons/Code_snippets/StringView"><code>StringView</code> — a C-like representation of strings based on typed arrays</a></li> + <li><a href="/en-US/docs/Web/API/DOMString/Binary">Binary strings</a></li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/string/match/index.html b/files/zh-tw/web/javascript/reference/global_objects/string/match/index.html new file mode 100644 index 0000000000..664b28462f --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/string/match/index.html @@ -0,0 +1,151 @@ +--- +title: String.prototype.match() +slug: Web/JavaScript/Reference/Global_Objects/String/match +translation_of: Web/JavaScript/Reference/Global_Objects/String/match +--- +<div>{{JSRef}}</div> + +<p>The <strong><code>match()</code></strong> method retrieves the matches when matching a <em>string</em> against a <em>regular expression</em>.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><var>str</var>.match(<var>regexp</var>)</pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>regexp</code></dt> + <dd>一個正規表達式的物件。 若傳入一個非正規表達式的物件<code>obj</code>,則會視為傳入 <code>new RegExp(obj)</code>。若只呼叫<code>match()</code>而沒有傳入任何參數,則會回傳內含一個空字串的陣列,即<code>[""]</code>。</dd> +</dl> + +<h3 id="Return_value">Return value</h3> + +<p>If the string matches the expression, it will return an {{jsxref("Array")}} containing the entire matched string as the first element, followed by any results captured in parentheses. If there were no matches, {{jsxref("null")}} is returned.</p> + +<h2 id="Description">Description</h2> + +<p>If the regular expression does not include the <code>g</code> flag, <code>str.match()</code> will return the same result as {{jsxref("RegExp.prototype.exec()", "RegExp.exec()")}}. The returned {{jsxref("Array")}} has an extra <code>input</code> property, which contains the original string that was parsed. In addition, it has an <code>index</code> property, which represents the zero-based index of the match in the string.</p> + +<p>If the regular expression includes the <code>g</code> flag, the method returns an {{jsxref("Array")}} containing all matched substrings rather than match objects. Captured groups are not returned. If there were no matches, the method returns {{jsxref("null")}}.</p> + +<h3 id="See_also_RegExp_methods">See also: <code>RegExp</code> methods</h3> + +<ul> + <li>If you need to know if a string matches a regular expression {{jsxref("RegExp")}}, use {{jsxref("RegExp.prototype.test()", "RegExp.test()")}}.</li> + <li>If you only want the first match found, you might want to use {{jsxref("RegExp.prototype.exec()", "RegExp.exec()")}} instead.</li> + <li>if you want to obtain capture groups and the global flag is set, you need to use {{jsxref("RegExp.prototype.exec()", "RegExp.exec()")}} instead.</li> +</ul> + +<h2 id="Examples">Examples</h2> + +<h3 id="Using_match()">Using <code>match()</code></h3> + +<p>In the following example, <code>match()</code> is used to find <code>'Chapter'</code> followed by 1 or more numeric characters followed by a decimal point and numeric character 0 or more times. The regular expression includes the <code>i</code> flag so that upper/lower case differences will be ignored.</p> + +<pre class="brush: js">var str = 'For more information, see Chapter 3.4.5.1'; +var re = /see (chapter \d+(\.\d)*)/i; +var found = str.match(re); + +console.log(found); + +// logs [ 'see Chapter 3.4.5.1', +// 'Chapter 3.4.5.1', +// '.1', +// index: 22, +// input: 'For more information, see Chapter 3.4.5.1' ] + +// 'see Chapter 3.4.5.1' is the whole match. +// 'Chapter 3.4.5.1' was captured by '(chapter \d+(\.\d)*)'. +// '.1' was the last value captured by '(\.\d)'. +// The 'index' property (22) is the zero-based index of the whole match. +// The 'input' property is the original string that was parsed.</pre> + +<h3 id="Using_global_and_ignore_case_flags_with_match()">Using global and ignore case flags with <code>match()</code></h3> + +<p>The following example demonstrates the use of the global and ignore case flags with <code>match()</code>. All letters A through E and a through e are returned, each its own element in the array.</p> + +<pre class="brush: js">var str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; +var regexp = /[A-E]/gi; +var matches_array = str.match(regexp); + +console.log(matches_array); +// ['A', 'B', 'C', 'D', 'E', 'a', 'b', 'c', 'd', 'e'] +</pre> + +<h3 id="Using_match()_with_no_parameter">Using <code>match()</code> with no parameter</h3> + +<pre class="brush: js">var str = "Nothing will come of nothing."; + +str.match(); // returns [""]</pre> + +<h3 id="A_non-RegExp_object_as_the_parameter">A non-RegExp object as the parameter</h3> + +<p>When the parameter is a string or a number, it is implicitly converted to a {{jsxref("RegExp")}} by using new RegExp(obj). If it is a positive number with a positive sign,the RegExp() method will ignore the positive sign. </p> + +<pre class="brush: js">var str1 = "NaN means not a number. Infinity contains -Infinity and +Infinity in JavaScript.", + str2 = "My grandfather is 65 years old and My grandmother is 63 years old.", + str3 = "The contract was declared null and void."; +str1.match("number"); // "number" is a string. returns ["number"] +str1.match(NaN); // the type of NaN is the number. returns ["NaN"] +str1.match(Infinity); // the type of Infinity is the number. returns ["Infinity"] +str1.match(+Infinity); // returns ["Infinity"] +str1.match(-Infinity); // returns ["-Infinity"] +str2.match(65); // returns ["65"] +str2.match(+65); // A number with a positive sign. returns ["65"] +str3.match(null); // returns ["null"]</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Initial definition. Implemented in JavaScript 1.2.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5.4.10', 'String.prototype.match')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.match', 'String.prototype.match')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.match', 'String.prototype.match')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.String.match")}}</p> + +<h2 id="Firefox-specific_notes">Firefox-specific notes</h2> + +<ul> + <li><code>flags</code> was a non standard second argument only available in Gecko : <var>str</var>.match(<var>regexp, flags</var>)</li> + <li>Starting with Gecko 27 {{geckoRelease(27)}}, this method has been adjusted to conform with the ECMAScript specification. When <code>match()</code> is called with a global regular expression, the {{jsxref("RegExp.lastIndex")}} property (if specified) will be reset to <code>0</code> ({{bug(501739)}}).</li> + <li>Starting with Gecko 39 {{geckoRelease(39)}}, the non-standard <code>flags</code> argument is deprecated and throws a console warning ({{bug(1142351)}}).</li> + <li>Starting with Gecko 47 {{geckoRelease(47)}}, the non-standard <code>flags</code> argument is no longer supported in non-release builds and will soon be removed entirely ({{bug(1245801)}}).</li> + <li>Starting with Gecko 49 {{geckoRelease(49)}}, the non-standard <code>flags</code> argument is no longer supported ({{bug(1108382)}}).</li> +</ul> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("RegExp")}}</li> + <li>{{jsxref("RegExp.prototype.exec()")}}</li> + <li>{{jsxref("RegExp.prototype.test()")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/string/padstart/index.html b/files/zh-tw/web/javascript/reference/global_objects/string/padstart/index.html new file mode 100644 index 0000000000..8a08d5924f --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/string/padstart/index.html @@ -0,0 +1,96 @@ +--- +title: String.prototype.padStart() +slug: Web/JavaScript/Reference/Global_Objects/String/padStart +translation_of: Web/JavaScript/Reference/Global_Objects/String/padStart +--- +<div>{{JSRef}}{{SeeCompatTable}}</div> + +<p><strong><code>padStart()</code></strong><code> 會將用給定用於填充的字串,以重複的方式,插入到目標字串的起頭(左側),直到目標字串到達指定長度。</code></p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><var>str</var>.padStart(<var>targetLength</var> [, <var>padString</var>])</pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>targetLength</code></dt> + <dd>目標字串被填充後的長度。如果此參數小於原字串的長度,那將直接返回原字串。</dd> + <dt><code>padString</code> {{optional_inline}}</dt> + <dd>用來填充的字串。如果填充字串太長,則由左側開始,擷取所需要的長度。此參數預設值是空白 " " (U+0020).</dd> +</dl> + +<h3 id="Return_value">Return value</h3> + +<p>目標字串被填充到指定長度後,所得的新字串。</p> + +<h2 id="Examples">Examples</h2> + +<pre class="brush: js">'abc'.padStart(10); // " abc" +'abc'.padStart(10, "foo"); // "foofoofabc" +'abc'.padStart(6,"123465"); // "123abc" +</pre> + +<h2 id="Specifications">Specifications</h2> + +<p>這個方法還沒有被納入 ECMAScript 標準。現在還只是個<a href="https://github.com/tc39/proposal-string-pad-start-end">提案</a>。</p> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome(57)}} </td> + <td>15</td> + <td>{{CompatGeckoDesktop(51)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatOpera(44)}}</td> + <td>{{CompatSafari(10)}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</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>Basic support</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatChrome(57)}}</td> + <td>{{CompatGeckoMobile(51)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatSafari(10)}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("String.padEnd()")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/string/prototype/index.html b/files/zh-tw/web/javascript/reference/global_objects/string/prototype/index.html new file mode 100644 index 0000000000..41c7333dc6 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/string/prototype/index.html @@ -0,0 +1,176 @@ +--- +title: String.prototype +slug: Web/JavaScript/Reference/Global_Objects/String/prototype +translation_of: Web/JavaScript/Reference/Global_Objects/String +--- +<div>{{JSRef}}</div> + +<p>The <strong><code>String.prototype</code></strong> property represents the {{jsxref("String")}} prototype object.</p> + +<div>{{js_property_attributes(0, 0, 0)}}</div> + +<h2 id="Description">Description</h2> + +<p>All {{jsxref("String")}} instances inherit from <code>String.prototype</code>. Changes to the <code>String</code> prototype object are propagated to all {{jsxref("String")}} instances.</p> + +<h2 id="Properties">Properties</h2> + +<dl> + <dt><code>String.prototype.constructor</code></dt> + <dd>Specifies the function that creates an object's prototype.</dd> + <dt>{{jsxref("String.prototype.length")}}</dt> + <dd>Reflects the length of the string.</dd> + <dt><code><em>N</em></code></dt> + <dd>Used to access the character in the <em>N</em>th position where <em>N</em> is a positive integer between 0 and one less than the value of {{jsxref("String.length", "length")}}. These properties are read-only.</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<h3 id="Methods_unrelated_to_HTML">Methods unrelated to HTML</h3> + +<dl> + <dt>{{jsxref("String.prototype.charAt()")}}</dt> + <dd>Returns the character (exactly one UTF-16 code unit) at the specified index.</dd> + <dt>{{jsxref("String.prototype.charCodeAt()")}}</dt> + <dd>Returns a number that is the UTF-16 code unit value at the given index.</dd> + <dt>{{jsxref("String.prototype.codePointAt()")}}</dt> + <dd>Returns a nonnegative integer Number that is the code point value of the UTF-16 encoded code point starting at the specified index.</dd> + <dt>{{jsxref("String.prototype.concat()")}}</dt> + <dd>Combines the text of two strings and returns a new string.</dd> + <dt>{{jsxref("String.prototype.includes()")}}</dt> + <dd>Determines whether one string may be found within another string.</dd> + <dt>{{jsxref("String.prototype.endsWith()")}}</dt> + <dd>Determines whether a string ends with the characters of another string.</dd> + <dt>{{jsxref("String.prototype.indexOf()")}}</dt> + <dd>Returns the index within the calling {{jsxref("String")}} object of the first occurrence of the specified value, or -1 if not found.</dd> + <dt>{{jsxref("String.prototype.lastIndexOf()")}}</dt> + <dd>Returns the index within the calling {{jsxref("String")}} object of the last occurrence of the specified value, or -1 if not found.</dd> + <dt>{{jsxref("String.prototype.localeCompare()")}}</dt> + <dd>Returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order.</dd> + <dt>{{jsxref("String.prototype.match()")}}</dt> + <dd>Used to match a regular expression against a string.</dd> + <dt>{{jsxref("String.prototype.normalize()")}}</dt> + <dd>Returns the Unicode Normalization Form of the calling string value.</dd> + <dt>{{jsxref("String.prototype.padEnd()")}}</dt> + <dd>Pads the current string from the end with a given string to create a new string from a given length.</dd> + <dt>{{jsxref("String.prototype.padStart()")}}</dt> + <dd>Pads the current string from the start with a given string to create a new string from a given length.</dd> + <dt><s class="obsoleteElement">{{jsxref("String.prototype.quote()")}} {{obsolete_inline}}</s></dt> + <dd><s class="obsoleteElement">Wraps the string in double quotes ("<code>"</code>").</s></dd> + <dt>{{jsxref("String.prototype.repeat()")}}</dt> + <dd>Returns a string consisting of the elements of the object repeated the given times.</dd> + <dt>{{jsxref("String.prototype.replace()")}}</dt> + <dd>Used to find a match between a regular expression and a string, and to replace the matched substring with a new substring.</dd> + <dt>{{jsxref("String.prototype.search()")}}</dt> + <dd>Executes the search for a match between a regular expression and a specified string.</dd> + <dt>{{jsxref("String.prototype.slice()")}}</dt> + <dd>Extracts a section of a string and returns a new string.</dd> + <dt>{{jsxref("String.prototype.split()")}}</dt> + <dd>Splits a {{jsxref("Global_Objects/String", "String")}} object into an array of strings by separating the string into substrings.</dd> + <dt>{{jsxref("String.prototype.startsWith()")}}</dt> + <dd>Determines whether a string begins with the characters of another string.</dd> + <dt>{{jsxref("String.prototype.substr()")}}</dt> + <dd>Returns the characters in a string beginning at the specified location through the specified number of characters.</dd> + <dt>{{jsxref("String.prototype.substring()")}}</dt> + <dd>Returns the characters in a string between two indexes into the string.</dd> + <dt>{{jsxref("String.prototype.toLocaleLowerCase()")}}</dt> + <dd>The characters within a string are converted to lower case while respecting the current locale. For most languages, this will return the same as {{jsxref("String.prototype.toLowerCase()", "toLowerCase()")}}.</dd> + <dt>{{jsxref("String.prototype.toLocaleUpperCase()")}}</dt> + <dd>The characters within a string are converted to upper case while respecting the current locale. For most languages, this will return the same as {{jsxref("String.prototype.toUpperCase()", "toUpperCase()")}}.</dd> + <dt>{{jsxref("String.prototype.toLowerCase()")}}</dt> + <dd>Returns the calling string value converted to lower case.</dd> + <dt>{{jsxref("String.prototype.toSource()")}} {{non-standard_inline}}</dt> + <dd>Returns an object literal representing the specified object; you can use this value to create a new object. Overrides the {{jsxref("Object.prototype.toSource()")}} method.</dd> + <dt>{{jsxref("String.prototype.toString()")}}</dt> + <dd>Returns a string representing the specified object. Overrides the {{jsxref("Object.prototype.toString()")}} method.</dd> + <dt>{{jsxref("String.prototype.toUpperCase()")}}</dt> + <dd>Returns the calling string value converted to uppercase.</dd> + <dt>{{jsxref("String.prototype.trim()")}}</dt> + <dd>Trims whitespace from the beginning and end of the string. Part of the ECMAScript 5 standard.</dd> + <dt>{{jsxref("String.prototype.trimLeft()")}} {{non-standard_inline}}</dt> + <dd>Trims whitespace from the left side of the string.</dd> + <dt>{{jsxref("String.prototype.trimRight()")}} {{non-standard_inline}}</dt> + <dd>Trims whitespace from the right side of the string.</dd> + <dt>{{jsxref("String.prototype.valueOf()")}}</dt> + <dd>Returns the primitive value of the specified object. Overrides the {{jsxref("Object.prototype.valueOf()")}} method.</dd> + <dt>{{jsxref("String.prototype.@@iterator()", "String.prototype[@@iterator]()")}}</dt> + <dd>Returns a new <code>Iterator</code> object that iterates over the code points of a String value, returning each code point as a String value.</dd> +</dl> + +<h3 id="HTML_wrapper_methods">HTML wrapper methods</h3> + +<p>These methods are of limited use, as they provide only a subset of the available HTML tags and attributes.</p> + +<dl> + <dt>{{jsxref("String.prototype.anchor()")}}</dt> + <dd>{{htmlattrxref("name", "a", "<a name=\"name\">")}} (hypertext target)</dd> + <dt>{{jsxref("String.prototype.big()")}} {{deprecated_inline}}</dt> + <dd>{{HTMLElement("big")}}</dd> + <dt>{{jsxref("String.prototype.blink()")}} {{deprecated_inline}}</dt> + <dd>{{HTMLElement("blink")}}</dd> + <dt>{{jsxref("String.prototype.bold()")}} {{deprecated_inline}}</dt> + <dd>{{HTMLElement("b")}}</dd> + <dt>{{jsxref("String.prototype.fixed()")}} {{deprecated_inline}}</dt> + <dd>{{HTMLElement("tt")}}</dd> + <dt>{{jsxref("String.prototype.fontcolor()")}} {{deprecated_inline}}</dt> + <dd>{{htmlattrxref("color", "font", "<font color=\"color\">")}}</dd> + <dt>{{jsxref("String.prototype.fontsize()")}} {{deprecated_inline}}</dt> + <dd>{{htmlattrxref("size", "font", "<font size=\"size\">")}}</dd> + <dt>{{jsxref("String.prototype.italics()")}} {{deprecated_inline}}</dt> + <dd>{{HTMLElement("i")}}</dd> + <dt>{{jsxref("String.prototype.link()")}}</dt> + <dd>{{htmlattrxref("href", "a", "<a href=\"url\">")}} (link to URL)</dd> + <dt>{{jsxref("String.prototype.small()")}} {{deprecated_inline}}</dt> + <dd>{{HTMLElement("small")}}</dd> + <dt>{{jsxref("String.prototype.strike()")}} {{deprecated_inline}}</dt> + <dd>{{HTMLElement("strike")}}</dd> + <dt>{{jsxref("String.prototype.sub()")}} {{deprecated_inline}}</dt> + <dd>{{HTMLElement("sub")}}</dd> + <dt>{{jsxref("String.prototype.sup()")}} {{deprecated_inline}}</dt> + <dd>{{HTMLElement("sup")}}</dd> +</dl> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5.3.1', 'String.prototype')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype', 'String.prototype')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype', 'String.prototype')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.String.prototype")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("String")}}</li> + <li>{{jsxref("Function.prototype")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/string/replace/index.html b/files/zh-tw/web/javascript/reference/global_objects/string/replace/index.html new file mode 100644 index 0000000000..1c42d9925f --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/string/replace/index.html @@ -0,0 +1,286 @@ +--- +title: String.prototype.replace() +slug: Web/JavaScript/Reference/Global_Objects/String/replace +translation_of: Web/JavaScript/Reference/Global_Objects/String/replace +--- +<div>{{JSRef}}</div> + +<p><strong><code>replace()</code></strong> 方法會傳回一個新字串,此新字串是透過將原字串與 <code>pattern</code> 比對,以 <code>replacement</code> 取代吻合處而生成。<code>pattern</code> 可以是字串或 {{jsxref("RegExp")}},而 <code>replacement</code> 可以是字串或函式(會在每一次匹配時被呼叫)。</p> + +<div class="note"> +<p>備註:原始的字串會保持不變。</p> +</div> + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox"><var>str</var>.replace(<var>regexp</var>|<var>substr</var>, <var>newSubstr</var>|<var>function</var>)</pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>regexp</code> (pattern)</dt> + <dd>{{jsxref("RegExp")}} 的物件或文字。 被比對出來的部分將會被取代為 <code>newSubStr</code> 或是取代為 <code>function</code> 的回傳值。</dd> + <dt><code>substr</code> (pattern)</dt> + <dd>要被 <code>newSubStr</code> 取代的 {{jsxref("String")}}。它被視為逐字字符串,並且不會被解釋為正則表達式。只會替換第一次出現。</dd> + <dt><code>newSubStr</code> (replacement)</dt> + <dd>The {{jsxref("String")}} that replaces the substring specified by the specified <code>regexp</code> or <code>substr</code> parameter. A number of special replacement patterns are supported; see the "<a href="#指定一個字串為參數">Specifying a string as a parameter</a>" section below.</dd> + <dt><code>function</code> (replacement)</dt> + <dd>A function to be invoked to create the new substring to be used to replace the matches to the given <code>regexp</code> or <code>substr</code>. The arguments supplied to this function are described in the "<a href="#指定一個函式為參數">Specifying a function as a parameter</a>" section below.</dd> +</dl> + +<h3 id="回傳值">回傳值</h3> + +<p>A new string with some or all matches of a pattern replaced by a replacement.</p> + +<h2 id="描述">描述</h2> + +<p>這個方法不會變更所呼叫的 {{jsxref("String")}}。它只會回傳新的字串。</p> + +<p>To perform a global search and replace, include the <code>g</code> switch in the regular expression.</p> + +<h3 id="指定一個字串為參數">指定一個字串為參數</h3> + +<p>The replacement string can include the following special replacement patterns:</p> + +<table class="fullwidth-table"> + <tbody> + <tr> + <td class="header">Pattern</td> + <td class="header">Inserts</td> + </tr> + <tr> + <td><code>$$</code></td> + <td>Inserts a "$".</td> + </tr> + <tr> + <td><code>$&</code></td> + <td>Inserts the matched substring.</td> + </tr> + <tr> + <td><code>$`</code></td> + <td>Inserts the portion of the string that precedes the matched substring.</td> + </tr> + <tr> + <td><code>$'</code></td> + <td>Inserts the portion of the string that follows the matched substring.</td> + </tr> + <tr> + <td><code>$<em>n</em></code></td> + <td>Where <code><em>n</em></code> is a positive integer less than 100, inserts the <em>n</em>th parenthesized submatch string, provided the first argument was a {{jsxref("RegExp")}} object.</td> + </tr> + </tbody> +</table> + +<h3 id="指定一個函式為參數">指定一個函式為參數</h3> + +<p>You can specify a function as the second parameter. In this case, the function will be invoked after the match has been performed. The function's result (return value) will be used as the replacement string. (Note: the above-mentioned special replacement patterns do <em>not</em> apply in this case.) Note that the function will be invoked multiple times for each full match to be replaced if the regular expression in the first parameter is global.</p> + +<p>The arguments to the function are as follows:</p> + +<table class="fullwidth-table"> + <tbody> + <tr> + <td class="header">Possible name</td> + <td class="header">Supplied value</td> + </tr> + <tr> + <td><code>match</code></td> + <td>The matched substring. (Corresponds to <code>$&</code> above.)</td> + </tr> + <tr> + <td><code>p1, p2, ...</code></td> + <td>The <em>n</em>th parenthesized submatch string, provided the first argument to <code>replace()</code> was a {{jsxref("RegExp")}} object. (Corresponds to <code>$1</code>, <code>$2</code>, etc. above.) For example, if <code>/(\a+)(\b+)/</code>, was given, <code>p1</code> is the match for <code>\a+</code>, and <code>p2</code> for <code>\b+</code>.</td> + </tr> + <tr> + <td><code>offset</code></td> + <td>The offset of the matched substring within the whole string being examined. (For example, if the whole string was <code>'abcd'</code>, and the matched substring was <code>'bc'</code>, then this argument will be 1.)</td> + </tr> + <tr> + <td><code>string</code></td> + <td>The whole string being examined.</td> + </tr> + </tbody> +</table> + +<p>(The exact number of arguments will depend on whether the first argument was a {{jsxref("RegExp")}} object and, if so, how many parenthesized submatches it specifies.)</p> + +<p>The following example will set <code>newString</code> to <code>'abc - 12345 - #$*%'</code>:</p> + +<pre class="brush: js">function replacer(match, p1, p2, p3, offset, string) { + // p1 is nondigits, p2 digits, and p3 non-alphanumerics + return [p1, p2, p3].join(' - '); +} +var newString = 'abc12345#$*%'.replace(/([^\d]*)(\d*)([^\w]*)/, replacer); +console.log(newString); // abc - 12345 - #$*% +</pre> + +<h2 id="範例">範例</h2> + +<h3 id="於_replace()_中定義正則表示式">於 <code>replace()</code> 中定義正則表示式</h3> + +<p>下例的正規表達式被定義為 <code>replace()</code>、並包含了忽略大小寫的 flag。</p> + +<pre class="brush: js">var str = 'Twas the night before Xmas...'; +var newstr = str.replace(/xmas/i, 'Christmas'); +console.log(newstr); // Twas the night before Christmas... +</pre> + +<p>上例會顯示「Twas the night before Christmas...」</p> + +<h3 id="使用_global_及_ignore_來配合_replace()">使用 <code>global</code> 及 <code>ignore</code> 來配合 <code>replace()</code></h3> + +<p>Global replace can only be done with a regular expression. In the following example, the regular expression includes the global and ignore case flags which permits <code>replace()</code> to replace each occurrence of 'apples' in the string with 'oranges'.</p> + +<pre class="brush: js">var re = /apples/gi; +var str = 'Apples are round, and apples are juicy.'; +var newstr = str.replace(re, 'oranges'); +console.log(newstr); // oranges are round, and oranges are juicy. +</pre> + +<p>上例會顯示「oranges are round, and oranges are juicy」。</p> + +<h3 id="替換字串中的單字">替換字串中的單字</h3> + +<p>下例程式將切換字串內的單字。對 replacement text 而言,程式會使用 <code>$1</code> and <code>$2</code> 的 replacement pattern。</p> + +<pre class="brush: js">var re = /(\w+)\s(\w+)/; +var str = 'John Smith'; +var newstr = str.replace(re, '$2, $1'); +console.log(newstr); // Smith, John +</pre> + +<p>上例會顯示「Smith, John」。</p> + +<h3 id="使用行內函式來修改匹配的字元">使用行內函式來修改匹配的字元</h3> + +<p>In this example, all occurrences of capital letters in the string are converted to lower case, and a hyphen is inserted just before the match location. The important thing here is that additional operations are needed on the matched item before it is given back as a replacement.</p> + +<p>The replacement function accepts the matched snippet as its parameter, and uses it to transform the case and concatenate the hyphen before returning.</p> + +<pre class="brush: js">function styleHyphenFormat(propertyName) { + function upperToHyphenLower(match, offset, string) { + return (offset ? '-' : '') + match.toLowerCase(); + } + return propertyName.replace(/[A-Z]/g, upperToHyphenLower); +} +</pre> + +<p>Given <code>styleHyphenFormat('borderTop')</code>, this returns 'border-top'.</p> + +<p>Because we want to further transform the <em>result</em> of the match before the final substitution is made, we must use a function. This forces the evaluation of the match prior to the {{jsxref("String.prototype.toLowerCase()", "toLowerCase()")}} method. If we had tried to do this using the match without a function, the {{jsxref("String.prototype.toLowerCase()", "toLowerCase()")}} would have no effect.</p> + +<pre class="brush: js">var newString = propertyName.replace(/[A-Z]/g, '-' + '$&'.toLowerCase()); // won't work +</pre> + +<p>This is because <code>'$&'.toLowerCase()</code> would be evaluated first as a string literal (resulting in the same <code>'$&'</code>) before using the characters as a pattern.</p> + +<h3 id="將華氏溫度置換成攝氏溫度">將華氏溫度置換成攝氏溫度</h3> + +<p>The following example replaces a Fahrenheit degree with its equivalent Celsius degree. The Fahrenheit degree should be a number ending with F. The function returns the Celsius number ending with C. For example, if the input number is 212F, the function returns 100C. If the number is 0F, the function returns -17.77777777777778C.</p> + +<p>The regular expression <code>test</code> checks for any number that ends with F. The number of Fahrenheit degree is accessible to the function through its second parameter, <code>p1</code>. The function sets the Celsius number based on the Fahrenheit degree passed in a string to the <code>f2c()</code> function. <code>f2c()</code> then returns the Celsius number. This function approximates Perl's <code>s///e</code> flag.</p> + +<pre class="brush: js">function f2c(x) { + function convert(str, p1, offset, s) { + return ((p1 - 32) * 5/9) + 'C'; + } + var s = String(x); + var test = /(-?\d+(?:\.\d*)?)F\b/g; + return s.replace(test, convert); +} +</pre> + +<h3 id="利用行內函式及正則表示式來避免使用_for_迴圈">利用行內函式及正則表示式來避免使用 <code>for</code> 迴圈</h3> + +<p>The following example takes a string pattern and converts it into an array of objects.</p> + +<p><strong>Input:</strong></p> + +<p>A string made out of the characters <code>x</code>, <code>-</code> and <code>_</code></p> + +<pre>x-x_ +x---x---x---x--- +x-xxx-xx-x- +x_x_x___x___x___ +</pre> + +<p><strong>Output:</strong></p> + +<p>An array of objects. An <code>'x'</code> denotes an <code>'on'</code> state, a <code>'-'</code> (hyphen) denotes an <code>'off'</code> state and an <code>'_'</code> (underscore) denotes the length of an <code>'on'</code> state.</p> + +<pre class="brush: json">[ + { on: true, length: 1 }, + { on: false, length: 1 }, + { on: true, length: 2 } + ... +] +</pre> + +<p><strong>Snippet:</strong></p> + +<pre class="brush: js">var str = 'x-x_'; +var retArr = []; +str.replace(/(x_*)|(-)/g, function(match, p1, p2) { + if (p1) { retArr.push({ on: true, length: p1.length }); } + if (p2) { retArr.push({ on: false, length: 1 }); } +}); + +console.log(retArr); +</pre> + +<p>This snippet generates an array of 3 objects in the desired format without using a <code>for</code> loop.</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('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Initial definition. Implemented in JavaScript 1.2.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5.4.11', 'String.prototype.replace')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.replace', 'String.prototype.replace')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.replace', 'String.prototype.replace')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<p class="hidden">本相容性表格使用結構化資料自動產生。想要貢獻的話,請看看 <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> 並發個 PR。</p> + +<p>{{Compat("javascript.builtins.String.replace")}}</p> + +<h2 id="Firefox-specific_notes">Firefox-specific notes</h2> + +<ul> + <li>Starting with Gecko 27 {{geckoRelease(27)}}, this method has been adjusted to conform with the ECMAScript specification. When <code>replace()</code> is called with a global regular expression, the {{jsxref("RegExp.lastIndex")}} property (if specified) will be reset to <code>0</code> ({{bug(501739)}}).</li> + <li>Starting with Gecko 39 {{geckoRelease(39)}}, the non-standard <code>flags</code> argument is deprecated and throws a console warning ({{bug(1142351)}}).</li> + <li>Starting with Gecko 47 {{geckoRelease(47)}}, the non-standard <code>flags</code> argument is no longer supported in non-release builds and will soon be removed entirely ({{bug(1245801)}}).</li> + <li>Starting with Gecko 49 {{geckoRelease(49)}}, the non-standard <code>flags</code> argument is no longer supported ({{bug(1108382)}}).</li> +</ul> + +<h2 id="參見">參見</h2> + +<ul> + <li>{{jsxref("String.prototype.match()")}}</li> + <li>{{jsxref("RegExp.prototype.exec()")}}</li> + <li>{{jsxref("RegExp.prototype.test()")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/string/tolowercase/index.html b/files/zh-tw/web/javascript/reference/global_objects/string/tolowercase/index.html new file mode 100644 index 0000000000..35b9dc71bc --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/string/tolowercase/index.html @@ -0,0 +1,77 @@ +--- +title: String.prototype.toLowerCase() +slug: Web/JavaScript/Reference/Global_Objects/String/toLowerCase +translation_of: Web/JavaScript/Reference/Global_Objects/String/toLowerCase +--- +<div>{{JSRef}}</div> + +<p><strong><code>toLowerCase()</code></strong> 函式会回传将字符串转换为英文小写字母后的结果。</p> + +<div>{{EmbedInteractiveExample("pages/js/string-tolowercase.html")}}</div> + + + +<h2 id="语法">语法</h2> + +<pre class="syntaxbox"><code><var>str</var>.toLowerCase()</code></pre> + +<h3 id="回传值">回传值</h3> + +<p>回传一组将原字串英文内容转换成英文小写字母后的结果。</p> + +<h2 id="描述">描述</h2> + +<p>The <code>toLowerCase()</code> 函式会回传一组将原字符串英文内容转换成英文小写字母后的结果。 <code>toLowerCase()</code> 并不会影响到原字符串 <code>str</code> 的内容值。</p> + +<h2 id="范例">范例</h2> + +<h3 id="使用toLowerCase()">使用<code>toLowerCase()</code></h3> + +<pre class="brush: js">console.log('ALPHABET'.toLowerCase()); // 'alphabet' +</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('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5.4.16', 'String.prototype.toLowerCase')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.tolowercase', 'String.prototype.toLowerCase')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.tolowercase', 'String.prototype.toLowerCase')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="浏览器相容性">浏览器相容性</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.String.toLowerCase")}}</p> + +<h2 id="参考">参考</h2> + +<ul> + <li>{{jsxref("String.prototype.toLocaleLowerCase()")}}</li> + <li>{{jsxref("String.prototype.toLocaleUpperCase()")}}</li> + <li>{{jsxref("String.prototype.toUpperCase()")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/typedarray/index.html b/files/zh-tw/web/javascript/reference/global_objects/typedarray/index.html new file mode 100644 index 0000000000..f37e7ac069 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/typedarray/index.html @@ -0,0 +1,268 @@ +--- +title: TypedArray +slug: Web/JavaScript/Reference/Global_Objects/TypedArray +tags: + - JavaScript + - TypedArray + - TypedArrays +translation_of: Web/JavaScript/Reference/Global_Objects/TypedArray +--- +<div>{{JSRef}}</div> + +<p><strong><em>TypedArray</em></strong> 物件表示了一個底層 <code><a href="https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/JavaScript_typed_arrays/ArrayBuffer">ArrayBuffer</a></code> 的類陣列(array-like)視圖,它能以限定的型別解讀、修改 <code>ArrayBuffer</code>。但並沒有名為 <code>TypedArray</code> 的內建物件,<code>TypedArray</code> 也不存在可直接呼叫的建構式。真正能夠使用的是幾個原型繼承自 <code>TypedArray</code> 的內建物件,它們可以建立限定成員型別的物件實體來操作 <code>ArrayBuffer</code>。這些 <code>TypedArray</code> 型別的物件僅為視圖,並不會存放資料,所有的資料皆實際儲存於 <code>ArrayBuffer</code> 物件當中。以下將說明每種限定成員型別之 <code>TypedArray</code> 的共同屬性與方法。</p> + +<div>{{EmbedInteractiveExample("pages/js/typedarray-constructor.html")}}</div> + + + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox">new<em> TypedArray</em>(length); +new <em>TypedArray</em>(typedArray); +new <em>TypedArray</em>(object); +new <em>TypedArray</em>(buffer [, byteOffset [, length]]); + +where <em>TypedArray()</em> is one of: + +Int8Array(); +Uint8Array(); +Uint8ClampedArray(); +Int16Array(); +Uint16Array(); +Int32Array(); +Uint32Array(); +Float32Array(); +Float64Array(); +</pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt>length</dt> + <dd>When called with a <code>length</code> argument, a typed array containing <code>length</code> zeroes is created.</dd> + <dt>typedArray</dt> + <dd>When called with a <code>typedArray</code> argument, which can be an object of any of the typed array types (such as <code>Int32Array</code>), the <code>typedArray</code> gets copied into a new typed array. Each value in <code>typedArray</code> is converted to the corresponding type of the constructor before being copied into the new array.</dd> + <dt>object</dt> + <dd>When called with an <code>object</code> argument, a new typed array is created as if by the <code><em>TypedArray</em>.from()</code> method.</dd> + <dt>buffer, byteOffset, length</dt> + <dd>When called with a <code>buffer</code>, and optionally a <code>byteOffset</code> and a <code>length</code> argument, a new typed array view is created that views the specified {{jsxref("ArrayBuffer")}}. The <code>byteOffset</code> and <code>length</code> parameters specify the memory range that will be exposed by the typed array view. If both are omitted, all of <code>buffer</code> is viewed; if only <code>length</code> is omitted, the remainder of <code>buffer</code> is viewed.</dd> +</dl> + +<h2 id="說明">說明</h2> + +<p>ECMAScript 2015 defines a <em>TypedArray</em> constructor that serves as the <code>[[Prototype]]</code> of all <em>TypedArray</em> constructors. This constructor is not directly exposed: there is no global <code>%TypedArray%</code> or <code>TypedArray</code> property. It is only directly accessible through <code>Object.getPrototypeOf(Int8Array)</code> and similar. All <em>TypedArray</em>s constructors inherit common properties from the <code>%TypedArray%</code> constructor function. Additionally, all typed array prototypes (<em>TypedArray</em><code>.prototype</code>) have <code>%TypedArray%.prototype</code> as their <code>[[Prototype]]</code>.</p> + +<p>The <code>%TypedArray%</code> constructor on its own is not particularly useful. Calling it or using it in a <code>new</code> expression will throw a <code>TypeError</code>, except when used during object creation in JS engines that support subclassing. There are at present no such engines, so <code>%TypedArray%</code> is only useful to polyfill functions or properties onto all <em>TypedArray</em> constructors.</p> + +<p>When creating an instance of a <em>TypedArray</em> (e.g. <code>Int8Array</code>), an array buffer is created internally in memory or, if an <code>ArrayBuffer</code> object is given as constructor argument, then this is used instead. The buffer address is saved as an internal property of the instance and all the methods of %<code>TypedArray</code>%.<code>prototype</code>, i.e. set value and get value etc., operate on that array buffer address.</p> + +<h3 id="Property_access">Property access</h3> + +<p>You can reference elements in the array using standard array index syntax (that is, using bracket notation). However, getting or setting indexed properties on typed arrays will not search in the prototype chain for this property, even when the indices are out of bound. Indexed properties will consult the {{jsxref("ArrayBuffer")}} and will never look at object properties. You can still use named properties, just like with all objects.</p> + +<pre class="brush: js">// Setting and getting using standard array syntax +var int16 = new Int16Array(2); +int16[0] = 42; +console.log(int16[0]); // 42 + +// Indexed properties on prototypes are not consulted (Fx 25) +Int8Array.prototype[20] = 'foo'; +(new Int8Array(32))[20]; // 0 +// even when out of bound +Int8Array.prototype[20] = 'foo'; +(new Int8Array(8))[20]; // undefined +// or with negative integers +Int8Array.prototype[-1] = 'foo'; +(new Int8Array(8))[-1]; // undefined + +// Named properties are allowed, though (Fx 30) +Int8Array.prototype.foo = 'bar'; +(new Int8Array(32)).foo; // "bar"</pre> + +<h2 id="TypedArray_物件">TypedArray 物件</h2> + +<table class="standard-table"> + <tbody> + <tr> + <td class="header">Type</td> + <td class="header">Value Range</td> + <td class="header">Size in bytes</td> + <td class="header">Description</td> + <td class="header">Web IDL type</td> + <td class="header">Equivalent C type</td> + </tr> + <tr> + <td>{{jsxref("Int8Array")}}</td> + <td>-128 to 127</td> + <td>1</td> + <td>8-bit two's complement signed integer</td> + <td><code>byte</code></td> + <td><code>int8_t</code></td> + </tr> + <tr> + <td>{{jsxref("Uint8Array")}}</td> + <td>0 to 255</td> + <td>1</td> + <td>8-bit unsigned integer</td> + <td><code>octet</code></td> + <td><code>uint8_t</code></td> + </tr> + <tr> + <td>{{jsxref("Uint8ClampedArray")}}</td> + <td>0 to 255</td> + <td>1</td> + <td>8-bit unsigned integer (clamped)</td> + <td><code>octet</code></td> + <td><code>uint8_t</code></td> + </tr> + <tr> + <td>{{jsxref("Int16Array")}}</td> + <td>-32768 to 32767</td> + <td>2</td> + <td>16-bit two's complement signed integer</td> + <td><code>short</code></td> + <td><code>int16_t</code></td> + </tr> + <tr> + <td>{{jsxref("Uint16Array")}}</td> + <td>0 to 65535</td> + <td>2</td> + <td>16-bit unsigned integer</td> + <td><code>unsigned short</code></td> + <td><code>uint16_t</code></td> + </tr> + <tr> + <td>{{jsxref("Int32Array")}}</td> + <td>-2147483648 to 2147483647</td> + <td>4</td> + <td>32-bit two's complement signed integer</td> + <td><code>long</code></td> + <td><code>int32_t</code></td> + </tr> + <tr> + <td>{{jsxref("Uint32Array")}}</td> + <td>0 to 4294967295</td> + <td>4</td> + <td>32-bit unsigned integer</td> + <td><code>unsigned long</code></td> + <td><code>uint32_t</code></td> + </tr> + <tr> + <td>{{jsxref("Float32Array")}}</td> + <td>1.2x10<sup>-38</sup> to 3.4x10<sup>38</sup></td> + <td>4</td> + <td>32-bit IEEE floating point number ( 7 significant digits e.g. 1.1234567)</td> + <td><code>unrestricted float</code></td> + <td><code>float</code></td> + </tr> + <tr> + <td>{{jsxref("Float64Array")}}</td> + <td>5.0x10<sup>-324</sup> to 1.8x10<sup>308</sup></td> + <td>8</td> + <td>64-bit IEEE floating point number (16 significant digits e.g. 1.123...15)</td> + <td><code>unrestricted double</code></td> + <td><code>double</code></td> + </tr> + </tbody> +</table> + +<h2 id="屬性">屬性</h2> + +<dl> + <dt>{{jsxref("TypedArray.BYTES_PER_ELEMENT")}}</dt> + <dd>Returns a number value of the element size for the different typed array objects.</dd> + <dt><em>TypedArray</em>.length</dt> + <dd>Length property whose value is 0.</dd> + <dt>{{jsxref("TypedArray.name")}}</dt> + <dd>Returns the string value of the constructor name. E.g "Int8Array".</dd> + <dt>{{jsxref("TypedArray.@@species", "get TypedArray[@@species]")}}</dt> + <dd>The constructor function that is used to create derived objects.</dd> + <dt>{{jsxref("TypedArray.prototype")}}</dt> + <dd>Prototype for the <em>TypedArray</em> objects.</dd> +</dl> + +<h2 id="方法">方法</h2> + +<dl> + <dt>{{jsxref("TypedArray.from()")}}</dt> + <dd>Creates a new typed array from an array-like or iterable object. See also {{jsxref("Array.from()")}}.</dd> + <dt>{{jsxref("TypedArray.of()")}}</dt> + <dd>Creates a new typed array with a variable number of arguments. See also {{jsxref("Array.of()")}}.</dd> +</dl> + +<h2 id="TypedArray_原型">TypedArray 原型</h2> + +<p>All <em>TypedArray</em>s inherit from {{jsxref("TypedArray.prototype")}}.</p> + +<h3 id="屬性_2">屬性</h3> + +<p>{{page('en-US/Web/JavaScript/Reference/Global_Objects/TypedArray/prototype','Properties')}}</p> + +<h3 id="方法_2">方法</h3> + +<p>{{page('en-US/Web/JavaScript/Reference/Global_Objects/TypedArray/prototype','Methods')}}</p> + +<h3 id="Methods_Polyfill">Methods Polyfill</h3> + +<p>Many of the methods used in Typed Arrays can be polyfilled using the methods present in regular Javascript Arrays. The following snippet of JavaScript demonstrates how you might polyfill any missing Typed Array methods.</p> + +<pre class="brush: js example-bad">var typedArrayTypes = [<code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int8Array" title="The Int8Array typed array represents an array of twos-complement 8-bit signed integers. The contents are initialized to 0. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).">Int8Array</a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" title="The Uint8Array typed array represents an array of 8-bit unsigned integers. The contents are initialized to 0. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).">Uint8Array</a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8ClampedArray" title="The Uint8ClampedArray typed array represents an array of 8-bit unsigned integers clamped to 0-255; if you specified a value that is out of the range of [0,255], 0 or 255 will be set instead; if you specify a non-integer, the nearest integer will be set. The contents are initialized to 0. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).">Uint8ClampedArray</a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int16Array" title="The Int16Array typed array represents an array of twos-complement 16-bit signed integers in the platform byte order. If control over byte order is needed, use DataView instead. The contents are initialized to 0. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).">Int16Array</a>, +</code> <code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint16Array" title="The Uint16Array typed array represents an array of 16-bit unsigned integers in the platform byte order. If control over byte order is needed, use DataView instead. The contents are initialized to 0. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).">Uint16Array</a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int32Array" title="The Int32Array typed array represents an array of twos-complement 32-bit signed integers in the platform byte order. If control over byte order is needed, use DataView instead. The contents are initialized to 0. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).">Int32Array</a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint32Array" title="The Uint32Array typed array represents an array of 32-bit unsigned integers in the platform byte order. If control over byte order is needed, use DataView instead. The contents are initialized to 0. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).">Uint32Array</a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float32Array" title="The Float32Array typed array represents an array of 32-bit floating point numbers (corresponding to the C float data type) in the platform byte order. If control over byte order is needed, use DataView instead. The contents are initialized to 0. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).">Float32Array</a>, </code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float64Array" title="The Float64Array typed array represents an array of 64-bit floating point numbers (corresponding to the C double data type) in the platform byte order. If control over byte order is needed, use DataView instead. The contents are initialized to 0. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation)."><code>Float64Array</code></a>]; + +for (var k in typedArrayTypes) + for (var v in Array.prototype) + if (Array.prototype.hasOwnProperty(v) && + !typedArrayTypes[k].prototype.hasOwnProperty(v)) + typedArrayTypes[k].prototype[v] = Array.prototype[v]; +</pre> + +<h2 id="規範">規範</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('Typed Array')}}</td> + <td>{{Spec2('Typed Array')}}</td> + <td>Defined as <code>TypedArray</code> and <code>ArrayBufferView</code> interface with typed array view types. Superseded by ECMAScript 6.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-typedarray-objects', 'TypedArray Objects')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition in an ECMA standard. Specified behaviour for indexed and named properties. Specified that <code>new</code> is required.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-typedarray-objects', 'TypedArray Objects')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + + + +<p>{{Compat("javascript.builtins.TypedArray")}}</p> + +<h2 id="相容性備註">相容性備註</h2> + +<p>Starting with ECMAScript 2015, <code>TypedArray</code> constructors require to be constructed with a {{jsxref("Operators/new", "new")}} operator. Calling a <code>TypedArray</code> constructor as a function without <code>new</code>, will throw a {{jsxref("TypeError")}} from now on.</p> + +<pre class="brush: js example-bad">var dv = Int8Array([1, 2, 3]); +// TypeError: calling a builtin Int8Array constructor +// without new is forbidden</pre> + +<pre class="brush: js example-good">var dv = new Int8Array([1, 2, 3]);</pre> + +<h2 id="參見">參見</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Typed_arrays" title="en/JavaScript typed arrays">JavaScript typed arrays</a></li> + <li>{{jsxref("ArrayBuffer")}}</li> + <li>{{jsxref("DataView")}}</li> +</ul> diff --git a/files/zh-tw/web/javascript/reference/global_objects/undefined/index.html b/files/zh-tw/web/javascript/reference/global_objects/undefined/index.html new file mode 100644 index 0000000000..f352c84d71 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/undefined/index.html @@ -0,0 +1,136 @@ +--- +title: undefined +slug: Web/JavaScript/Reference/Global_Objects/undefined +tags: + - JavaScript +translation_of: Web/JavaScript/Reference/Global_Objects/undefined +--- +<div>{{jsSidebar("Objects")}}</div> + +<p>The global <code><strong>undefined</strong></code> property represents the primitive value <code>{{Glossary("Undefined", "undefined")}}</code>. It is one of JavaScript's {{Glossary("Primitive", "primitive types")}}.</p> + +<p>{{js_property_attributes(0,0,0)}}</p> + +<div>{{EmbedInteractiveExample("pages/js/globalprops-undefined.html")}}</div> + + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox"><code>undefined</code></pre> + +<h2 id="描述">描述</h2> + +<p><code>undefined</code> is a property of the <em>global object</em>; i.e., it is a variable in global scope. The initial value of <code>undefined</code> is the primitive value <code>{{Glossary("Undefined", "undefined")}}</code>.</p> + +<p>In modern browsers (JavaScript 1.8.5 / Firefox 4+), <code>undefined</code> is a non-configurable, non-writable property per the ECMAScript 5 specification. Even when this is not the case, avoid overriding it.</p> + +<p>A variable that has not been assigned a value is of type undefined. A method or statement also returns <code>undefined</code> if the variable that is being evaluated does not have an assigned value. A function returns <code>undefined</code> if a value was not {{jsxref("Statements/return", "returned")}}.</p> + +<div class="warning"> +<p>While it is possible to use it as an {{Glossary("Identifier", "identifier")}} (variable name) in any scope other than the global scope (because <code>undefined</code> is not a {{jsxref("Reserved_Words", "reserved word")}}), doing so is a very bad idea that will make your code difficult to maintain and debug.</p> + +<pre class="brush: js">//DON'T DO THIS + +// logs "foo string" +(function() { var undefined = 'foo'; console.log(undefined, typeof undefined); })(); + +// logs "foo string" +(function(undefined) { console.log(undefined, typeof undefined); })('foo'); +</pre> +</div> + +<h2 id="範例">範例</h2> + +<h3 id="Strict_equality_and_undefined">Strict equality and <code>undefined</code></h3> + +<p>You can use <code>undefined</code> and the strict equality and inequality operators to determine whether a variable has a value. In the following code, the variable <code>x</code> is not defined, and the <code>if</code> statement evaluates to true.</p> + +<pre class="brush: js">var x; +if (x === undefined) { + // these statements execute +} +else { + // these statements do not execute +} +</pre> + +<div class="note"> +<p>備註:The strict equality operator rather than the standard equality operator must be used here, because <code>x == undefined</code> also checks whether <code>x</code> is <code>null</code>, while strict equality doesn't. <code>null</code> is not equivalent to <code>undefined</code>. See {{jsxref("Operators/Comparison_Operators", "comparison operators")}} for details.</p> +</div> + +<h3 id="Typeof_operator_and_undefined"><code>Typeof</code> operator and <code>undefined</code></h3> + +<p>Alternatively, {{jsxref("Operators/typeof", "typeof")}} can be used:</p> + +<pre class="brush: js">var x; +if (typeof x === 'undefined') { + // these statements execute +} +</pre> + +<p>One reason to use {{jsxref("Operators/typeof", "typeof")}} is that it does not throw an error if the variable has not been declared.</p> + +<pre class="brush: js">// x has not been declared before +if (typeof x === 'undefined') { // evaluates to true without errors + // these statements execute +} + +if (x === undefined) { // throws a ReferenceError + +} +</pre> + +<p>However, this kind of technique should be avoided. JavaScript is a statically scoped language, so knowing if a variable is declared can be read by seeing whether it is declared in an enclosing context. The only exception is the global scope, but the global scope is bound to the global object, so checking the existence of a variable in the global context can be done by checking the existence of a property on the <em>global object</em> (using the {{jsxref("Operators/in", "in")}} operator, for instance).</p> + +<h3 id="Void_operator_and_undefined"><code>Void</code> operator and <code>undefined</code></h3> + +<p>The {{jsxref("Operators/void", "void")}} operator is a third alternative.</p> + +<pre class="brush: js">var x; +if (x === void 0) { + // these statements execute +} + +// y has not been declared before +if (y === void 0) { + // throws a - Uncaught ReferenceError: y is not defined +} +</pre> + +<h2 id="規範">規範</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1', '#sec-4.3.9', 'undefined')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.3.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.1.1.3', 'undefined')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-undefined', 'undefined')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-undefined', 'undefined')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + + + +<p>{{Compat("javascript.builtins.undefined")}}</p> diff --git a/files/zh-tw/web/javascript/reference/global_objects/urierror/index.html b/files/zh-tw/web/javascript/reference/global_objects/urierror/index.html new file mode 100644 index 0000000000..be0bb96d13 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/urierror/index.html @@ -0,0 +1,131 @@ +--- +title: URIError +slug: Web/JavaScript/Reference/Global_Objects/URIError +translation_of: Web/JavaScript/Reference/Global_Objects/URIError +--- +<div>{{JSRef}}</div> + +<p><code><strong>URIError</strong></code> 物件在全域的URI處理函式被錯誤使用時作為一個錯誤被拋出。</p> + +<h2 id="語法">語法</h2> + +<pre class="syntaxbox"><code>new URIError([<var>message</var>[, <var>fileName</var>[, <var>lineNumber</var>]]])</code></pre> + +<h3 id="參數">參數</h3> + +<dl> + <dt><code>message</code></dt> + <dd>可選。具人類可讀性的錯誤說明</dd> + <dt><code>fileName</code> {{non-standard_inline}}</dt> + <dd>可選。包含造成錯誤發生的程式碼的檔案名稱</dd> + <dt><code>lineNumber</code> {{non-standard_inline}}</dt> + <dd>可選。造成錯誤發生的程式碼行號</dd> +</dl> + +<h2 id="說明">說明</h2> + +<p><code>URIError</code> 在全域的URI處理函式被傳入了一個錯誤編碼的URI時被拋出。</p> + +<h2 id="屬性">屬性</h2> + +<dl> + <dt>{{jsxref("URIError.prototype")}}</dt> + <dd>允許對一個 <code>URIError</code> 物件增加其屬性。</dd> +</dl> + +<h2 id="方法">方法</h2> + +<p>普遍的 <code>URIError</code> 自身沒有包含方法,儘管他的確從原型鍊中繼承了一些。</p> + +<h2 id="URIError_物件實體"><code>URIError</code> 物件實體</h2> + +<h3 id="屬性_2">屬性</h3> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/URIError/prototype', 'Properties')}}</div> + +<h3 id="方法_2">方法</h3> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/URIError/prototype', 'Methods')}}</div> + +<h2 id="範例">範例</h2> + +<h3 id="Catch_一個_URIError">Catch 一個 <code>URIError</code></h3> + +<pre class="brush: js">try { + decodeURIComponent('%'); +} catch (e) { + console.log(e instanceof URIError); // true + console.log(e.message); // "malformed URI sequence" + console.log(e.name); // "URIError" + console.log(e.fileName); // "Scratchpad/1" + console.log(e.lineNumber); // 2 + console.log(e.columnNumber); // 2 + console.log(e.stack); // "@Scratchpad/2:2:3\n" +} +</pre> + +<h3 id="生成一個_URIError">生成一個 <code>URIError</code></h3> + +<pre class="brush: js">try { + throw new URIError('Hello', 'someFile.js', 10); +} catch (e) { + console.log(e instanceof URIError); // true + console.log(e.message); // "Hello" + console.log(e.name); // "URIError" + console.log(e.fileName); // "someFile.js" + console.log(e.lineNumber); // 10 + console.log(e.columnNumber); // 0 + console.log(e.stack); // "@Scratchpad/2:2:9\n" +} +</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('ES3', '#sec-15.11.6.6', 'URIError')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Initial definition</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.11.6.6', 'URIError')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-native-error-types-used-in-this-standard-urierror', 'URIError')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-native-error-types-used-in-this-standard-urierror', 'URIError')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="瀏覽器相容性">瀏覽器相容性</h2> + +<div> + + +<p>{{Compat("javascript.builtins.URIError")}}</p> +</div> + +<h2 id="另見">另見</h2> + +<ul> + <li>{{jsxref("Error")}}</li> + <li>{{jsxref("URIError.prototype")}}</li> + <li>{{jsxref("Global_Objects/decodeURI", "decodeURI()")}}</li> + <li>{{jsxref("Global_Objects/decodeURIComponent", "decodeURIComponent()")}}</li> + <li>{{jsxref("Global_Objects/encodeURI", "encodeURI()")}}</li> + <li>{{jsxref("Global_Objects/encodeURIComponent", "encodeURIComponent()")}}</li> +</ul> |