js实现push
实现数组的 push 方法
在 JavaScript 中,Array.prototype.push 方法用于向数组末尾添加一个或多个元素,并返回新的数组长度。以下是几种实现方式:

方法一:直接模拟原生 push 方法

Array.prototype.myPush = function(...items) {
for (let item of items) {
this[this.length] = item;
}
return this.length;
};
方法二:使用展开运算符
Array.prototype.myPush = function(...items) {
const newArray = [...this, ...items];
this.length = 0;
newArray.forEach(item => this[this.length] = item);
return this.length;
};
方法三:使用 concat 方法
Array.prototype.myPush = function(...items) {
const newArray = this.concat(items);
this.length = 0;
newArray.forEach(item => this[this.length] = item);
return this.length;
};
使用示例
const arr = [1, 2, 3];
const newLength = arr.myPush(4, 5);
console.log(arr); // [1, 2, 3, 4, 5]
console.log(newLength); // 5
注意事项
- 自定义 push 方法会修改原数组
- 可以一次添加多个元素
- 返回的是新数组的长度
- 避免在原型方法中使用箭头函数,因为箭头函数没有自己的 this 绑定






