js实现pop
实现数组的 pop 方法
在 JavaScript 中,数组的 pop 方法用于移除并返回数组的最后一个元素。以下是几种实现方式:
原生方法
直接使用 JavaScript 内置的 pop 方法:
const arr = [1, 2, 3];
const lastElement = arr.pop();
console.log(lastElement); // 3
console.log(arr); // [1, 2]
手动实现
通过修改数组的 length 属性来模拟 pop 方法:
function customPop(arr) {
if (arr.length === 0) return undefined;
const lastElement = arr[arr.length - 1];
arr.length = arr.length - 1;
return lastElement;
}
const arr = [1, 2, 3];
const lastElement = customPop(arr);
console.log(lastElement); // 3
console.log(arr); // [1, 2]
使用 splice 方法
利用 splice 方法移除最后一个元素:
function customPop(arr) {
const lastElement = arr.splice(-1, 1)[0];
return lastElement;
}
const arr = [1, 2, 3];
const lastElement = customPop(arr);
console.log(lastElement); // 3
console.log(arr); // [1, 2]
注意事项
- 如果数组为空,
pop方法返回undefined。 pop方法会修改原数组,而不是返回一个新数组。- 手动实现时需要注意边界条件(如空数组)。







