shift() 方法从数组中删除第一个元素,并返回该元素的值。此方法更改数组的长度。

返回值 

从数组中删除的元素; 如果数组为空则返回undefined 。 

语法

arr.shift()

描述

shift 方法移除索引为 0 的元素(即第一个元素),并返回被移除的元素,其他元素的索引值随之减 1。如果 length 属性的值为 0 (长度为 0),则返回 undefined

shift 方法并不局限于数组:这个方法能够通过 callapply 方法作用于类似数组的对象上。但是对于没有 length 属性(从0开始的一系列连续的数字属性的最后一个)的对象,调用该方法可能没有任何意义。

示例

移除数组中的一个元素

以下代码显示了删除其第一个元素之前和之后的myFish数组。它还显示已删除的元素:

let myFish = ['angel', 'clown', 'mandarin', 'surgeon'];

console.log('调用 shift 之前: ' + myFish);
// "调用 shift 之前: angel,clown,mandarin,surgeon"

var shifted = myFish.shift(); 

console.log('调用 shift 之后: ' + myFish); 
// "调用 shift 之后: clown,mandarin,surgeon" 

console.log('被删除的元素: ' + shifted); 
// "被删除的元素: angel"

规范

规范 状态 备注
ECMAScript 3rd Edition (ECMA-262) Standard Initial definition. Implemented in JavaScript 1.2.
ECMAScript 5.1 (ECMA-262)
Array.prototype.shift
Standard  
ECMAScript 2015 (6th Edition, ECMA-262)
Array.prototype.shift
Standard  
ECMAScript Latest Draft (ECMA-262)
Array.prototype.shift
Draft  

浏览器支持

Update compatibility data on GitHub
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidEdge MobileFirefox for AndroidOpera for AndroidSafari on iOSSamsung InternetNode.js
shiftChrome Full support 1Edge Full support 12Firefox Full support 1IE Full support 5.5Opera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesEdge Mobile Full support YesFirefox Android Full support 4Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yesnodejs Full support Yes

Legend

Full support  
Full support

相关链接