Array.prototype.shift()

概述

shift() 方法删除一个数组的第一个元素并返回这个元素. 该方法会改变数组的长度.

语法

arr.shift()

描述

shift 方法移除位于第0个索引的元素并连续降低之后的索引值(shifts the values at consecutive indexes down), 并返回被移除的元素值. 如果 length 属性值为0, 返回undefined .

shift 被有意的设计成通用(generic); 该方法可以像作用于数组一样 called or applied 作用于对象上. 当对象不包含 length 属性时, 无意义的0值length属性会被添加(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);

var shifted = myFish.shift();

console.log("myFish after: " + myFish);
console.log("Removed this element: " + shifted);

这个例子显示如下:

myFish before: angel,clown,mandarin,surgeon
myFish after: clown,mandarin,surgeon
Removed this element: angel

规范

Specification Status Comment
ECMAScript 3rd Edition Standard Initial definition. Implemented in JavaScript 1.2
ECMAScript Language Specification 5.1th Edition (ECMA-262) Standard  
ECMAScript Language Specification 6th Edition (ECMA-262) 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)

参见

Document Tags and Contributors

Contributors to this page: endlesswind
最后编辑者: endlesswind,