当前位置:首页 > JavaScript

js实现push

2026-02-01 12:39:13JavaScript

实现数组的 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 方法

js实现push

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 绑定

标签: jspush
分享给朋友:

相关文章

js 实现倒计时

js 实现倒计时

实现倒计时的基本方法 使用 JavaScript 实现倒计时可以通过 setInterval 或 setTimeout 结合日期计算来完成。以下是两种常见实现方式。 使用 setInterval 实…

js实现复制功能

js实现复制功能

使用 document.execCommand 方法 这种方法适用于较旧的浏览器,但在现代浏览器中可能被逐步淘汰。通过创建一个临时的 textarea 元素,将文本内容放入其中,然后执行复制命令。…

js实现pdf在线预览

js实现pdf在线预览

使用PDF.js实现PDF在线预览 PDF.js是由Mozilla开发的一个开源JavaScript库,可以在网页中直接渲染PDF文件。以下是实现PDF在线预览的步骤: 引入PDF.js库 在HT…

js实现换肤

js实现换肤

使用CSS变量实现换肤 通过CSS变量可以轻松实现主题切换功能。CSS变量在根元素中定义,通过JavaScript动态修改这些变量值。 :root { --primary-color: #349…

js分组实现

js分组实现

分组实现方法 在JavaScript中,可以通过多种方式实现数组或对象的分组操作。以下是几种常见的方法: 使用Array.prototype.reduce() 通过reduce方法可以轻松实现数组分…

js实现图表

js实现图表

在JavaScript中实现图表通常使用流行的图表库,以下是几种常见的方法和工具: 使用Chart.js Chart.js是一个简单灵活的库,适合快速生成响应式图表。安装方式包括CDN引入或npm安…