📜  JavaScript数组shift()(1)

📅  最后修改于: 2023-12-03 15:16:18.203000             🧑  作者: Mango

JavaScript数组shift()

在JavaScript中,数组是一种特殊的对象类型,可以容纳多个值,并通过索引进行访问。shift()是JavaScript数组的一个函数,可用于删除数组中的第一个元素并返回该元素。

语法
array.shift()

shift()函数不需要传入任何参数。

返回值

shift()函数的返回值是被删除的元素。如果数组为空,则返回undefined。

使用示例
移除第一个元素

下面的示例演示了如何使用shift()函数来移除数组的第一个元素。

const cars = ['BMW', 'Mercedes', 'Audi'];
const removedCar = cars.shift();

console.log(removedCar); // Output: 'BMW'
console.log(cars); // Output: ['Mercedes', 'Audi']

在这个例子中,我们创建了一个名为cars的数组,并使用shift()函数将数组的第一个元素'BWM'删除并返回。删除后,数组cars的新值为['Mercedes', 'Audi']。

处理空数组

在空数组上调用shift()函数将返回undefined。

const emptyArray = [];
const removedItem = emptyArray.shift();

console.log(removedItem); // Output: undefined
console.log(emptyArray); // Output: []

在这个例子中,我们创建了一个空数组emptyArray,并使用shift()函数删除第一个元素。由于这个数组是空的,因此shift()函数返回undefined。

总结

shift()函数是JavaScript数组的一个函数,可用于删除数组中的第一个元素并返回该元素。它返回被删除元素的值,如果数组为空,则返回undefined。因此,在使用shift()函数时需格外小心。