试一试
const array = [1, 2, 3];
const firstElement = array.shift();
console.log(array);
// Expected output: Array [2, 3]
console.log(firstElement);
// Expected output: 1
语法
js
shift()
参数
无。
返回值
从数组中移除的元素;如果数组为空,则返回 undefined。
描述
shift() 方法将所有值向左移动 1 位,并将长度减 1,从而移除第一个元素。如果 length 属性为 0,则返回 undefined。
pop() 方法与 shift() 的行为类似,但作用于数组的最后一个元素。
shift() 方法是 变异方法。它会改变 this 的长度和内容。如果您希望 this 的值保持不变,但返回一个移除第一个元素的新数组,可以使用 arr.slice(1) 来代替。
shift() 方法是 通用的。它只要求 this 值具有 length 属性和整数键属性。尽管字符串也类似数组,但此方法不适用于字符串,因为字符串是不可变的。
示例
移除数组中的元素
以下代码显示了 myFish 数组在移除第一个元素之前和之后的状态。它还显示了被移除的元素。
js
const myFish = ["angel", "clown", "mandarin", "surgeon"];
console.log("myFish before:", myFish);
// myFish before: ['angel', 'clown', 'mandarin', 'surgeon']
const shifted = myFish.shift();
console.log("myFish after:", myFish);
// myFish after: ['clown', 'mandarin', 'surgeon']
console.log("Removed this element:", shifted);
// Removed this element: angel
在 while 循环中使用 shift() 方法
shift() 方法通常用作 while 循环中的条件。在下面的示例中,每次迭代都会从数组中移除下一个元素,直到数组为空为止。
js
const names = ["Andrew", "Tyrone", "Paul", "Maria", "Gayatri"];
while (typeof (i = names.shift()) !== "undefined") {
console.log(i);
}
// Andrew, Tyrone, Paul, Maria, Gayatri
在非数组对象上调用 shift()
shift() 方法读取 this 的 length 属性。如果 规范化的长度 为 0,则 length 会再次设置为 0(而之前它可能是负数或 undefined)。否则,将返回索引为 0 的属性,并将其余属性向左移动一位。索引为 length - 1 的属性将被 删除,并且 length 属性会减一。
js
const arrayLike = {
length: 3,
unrelated: "foo",
2: 4,
};
console.log(Array.prototype.shift.call(arrayLike));
// undefined, because it is an empty slot
console.log(arrayLike);
// { '1': 4, length: 2, unrelated: 'foo' }
const plainObj = {};
// There's no length property, so the length is 0
Array.prototype.shift.call(plainObj);
console.log(plainObj);
// { length: 0 }
规范
| 规范 |
|---|
| ECMAScript® 2026 语言规范 # sec-array.prototype.shift |
浏览器兼容性
加载中…