JavaScript数组shift()方法

shift()是 JS 数组的一个方法。作用是:从数组的开头移除并返回第一个元素。

shift

它还同时产生一个作用是:修改原始数组,使其长度减1。

语法如下:

array.shift()

代码示例:

const arr = [1, 2, 3, 4, 5];
const firstElement = arr.shift();

console.log(firstElement); // 输出:1
console.log(arr); // 输出:[2, 3, 4, 5]

这个例子中,数组arr的第一个元素是1,调用arr.shift()1就会被移除并返回给firstElement,此时,数组arr也被改变了,变成了[2, 3, 4, 5]

要注意一点,shift()会修改原始数组,所以你在使用shift()前要确保不会影响到其他部分的代码逻辑。

还有,如果数组为空,shift()方法将返回undefined