js shift实现
使用 shift() 方法移除数组的第一个元素
shift() 是 JavaScript 数组的内置方法,用于移除数组的第一个元素并返回该元素。此操作会改变原数组的长度。
语法:
array.shift()
返回值:被移除的元素(如果数组为空则返回 undefined)。
基本用法示例
const fruits = ['apple', 'banana', 'orange'];
const removedFruit = fruits.shift();
console.log(removedFruit); // 输出: 'apple'
console.log(fruits); // 输出: ['banana', 'orange']
处理空数组的情况
如果数组为空,shift() 会返回 undefined,且数组保持不变:
const emptyArray = [];
const result = emptyArray.shift();
console.log(result); // 输出: undefined
console.log(emptyArray); // 输出: []
与 pop() 方法的对比
shift()移除数组的第一个元素。pop()移除数组的最后一个元素。
const numbers = [1, 2, 3];
numbers.shift(); // 移除 1
numbers.pop(); // 移除 3
console.log(numbers); // 输出: [2]
性能注意事项
shift() 操作的时间复杂度为 O(n),因为需要将所有剩余元素向前移动一位。对于大型数组,频繁使用 shift() 可能影响性能。如果需要高效地从头部操作数据,可考虑使用链表或其他数据结构。
实际应用场景
适合需要队列(FIFO)行为的场景,例如任务调度:

const taskQueue = ['task1', 'task2', 'task3'];
while (taskQueue.length > 0) {
const currentTask = taskQueue.shift();
console.log(`Processing: ${currentTask}`);
}
// 依次输出: Processing: task1, Processing: task2, Processing: task3






