首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

array.shift

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

代码语言:javascript
复制
var a = [1, 2, 3];
var b = a.shift();

console.log(a); // [2, 3]
console.log(b); // 1

语法

代码语言:javascript
复制
arr.shift()

返回值

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

描述

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

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

示例

移除数组中的一个元素

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

代码语言:javascript
复制
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

规范

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 Latest Draft (ECMA-262)The definition of 'Array.prototype.shift' in that specification.

Living Standard

浏览器兼容性

Feature

Chrome

Edge

Firefox

Internet Explorer

Opera

Safari

Basic Support

1

(Yes)

1

5.5

(Yes)

(Yes)

Feature

Android

Chrome for Android

Edge mobile

Firefox for Android

IE mobile

Opera Android

iOS Safari

Basic Support

(Yes)

(Yes)

(Yes)

1

(Yes)

(Yes)

(Yes)

扫码关注腾讯云开发者

领取腾讯云代金券