--- 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>