diff options
Diffstat (limited to 'files/zh-tw/web/javascript/reference/global_objects/array')
33 files changed, 5998 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> |