此文件需要編輯審查。看看您能幫什麼忙。
正在翻譯中。
shift()
方法 (method) 會從陣列移除第一個元素 (element),並回傳該元素。此方法會改變陣列的長度。
var a = [1, 2, 3]; a.shift(); console.log(a); // [2, 3]
語法
arr.shift()
回傳值
移除的元素。
描述
The shift
method removes the element at the zeroeth index and shifts the values at consecutive indexes down, then returns the removed value. If the length
property is 0, undefined
is returned.
shift
is intentionally generic; this method can be called or applied to objects resembling arrays. Objects which do not contain a length
property reflecting the last in a series of consecutive, zero-based numerical properties may not behave in any meaningful manner.
範例
從陣列移除單個元素
以下的程式碼會印出 myFish 陣列移除第一個元素之前跟之後的內容,也印出了移除的元素:
var myFish = ['angel', 'clown', 'mandarin', 'surgeon']; console.log('myFish before: ' + 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"
規格
Specification | Status | Comment |
---|---|---|
ECMAScript 3rd Edition (ECMA-262) | Standard | Initial definition. Implemented in JavaScript 1.2. |
ECMAScript 5.1 (ECMA-262) The definition of 'Array.prototype.shift' in that specification. |
Standard | |
ECMAScript 2015 (6th Edition, ECMA-262) The definition of 'Array.prototype.shift' in that specification. |
Standard | |
ECMAScript 2017 Draft (ECMA-262) The definition of 'Array.prototype.shift' in that specification. |
Draft |
瀏覽器相容性
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Basic support | 1.0 | 1.0 (1.7 or earlier) | 5.5 | (Yes) | (Yes) |
Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|
Basic support | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |