shift()
方法从数组中删除第一个元素,并返回该元素的值。此方法更改数组的长度。
let a = [1, 2, 3]; let b = a.shift(); console.log(a); // [2, 3] console.log(b); // 1
返回值
从数组中删除的元素; 如果数组为空则返回undefined
。
语法
arr.shift()
描述
shift
方法移除索引为 0 的元素(即第一个元素),并返回被移除的元素,其他元素的索引值随之减 1。如果 length
属性的值为 0 (长度为 0),则返回 undefined
。
shift
方法并不局限于数组:这个方法能够通过 call
或 apply
方法作用于类似数组的对象上。但是对于没有 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 |
浏览器支持
We're converting our compatibility data into a machine-readable JSON format. This compatibility table still uses the old format, because we haven't yet converted the data it contains. Find out how you can help!
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) |
相关链接
文档标签和贡献者
标签:
此页面的贡献者:
badfl,
LemonGirl,
micheal-death,
xgqfrms-GitHub,
Ende93,
pd4d10,
teoli,
AlexChao,
ziyunfei,
endlesswind
最后编辑者:
badfl,