You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JS通过class创建对象push入数组后新对象覆盖旧值如何解决

问题根因
  • 数组push逻辑本身没有问题,你可以打开浏览器控制台查看myLibrary数组,所有创建的Book实例都完整保存在数组中,没有被覆盖
  • 出现内容覆盖的原因是页面仅存在一组固定的h1、h2、h3标签,遍历数组时反复给这三个标签赋值,最终只会展示数组最后一个元素的内容
修正方案

1. 修改HTML结构

新增专门用来展示书籍列表的容器,替换原固定的三个标题标签:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Document</title>
</head>
<body>
  <input type="text" id="title" placeholder="书名" />
  <input type="text" id="author" placeholder="作者" />
  <input type="number" id="pages" placeholder="页数" />
  <!-- 新增书籍列表容器 -->
  <div id="bookList"></div>
  <button>Submit</button>

  <script src="app.js"></script>
</body>
</html>

2. 修改JS渲染逻辑

每次渲染前清空列表容器,为数组中每一本书单独创建DOM元素插入容器:

const title = document.querySelector("#title");
const author = document.querySelector("#author");
const pages = document.querySelector("#pages");
const submit = document.querySelector("button");
// 获取书籍列表容器
const bookList = document.querySelector("#bookList");

let myLibrary = [];

class Book {
  constructor(title, author, pages) {
    this.title = title;
    this.author = author;
    this.pages = pages;
    this.words = [];
  }
};

submit.addEventListener("click", () => {
  if (title.value === "" || author.value === "" || pages.value === "") {
    return;
  }
  // 新增书籍到数组
  myLibrary.push(new Book(title.value, author.value, pages.value));
  // 清空输入框
  title.value = "";
  author.value = "";
  pages.value = "";
  // 清空列表容器后重新渲染所有书籍
  bookList.innerHTML = "";
  myLibrary.forEach(book => {
    // 为每本书创建独立的DOM节点
    const bookItem = document.createElement("div");
    bookItem.innerHTML = `
      <h1>书名:${book.title}</h1>
      <h2>作者:${book.author}</h2>
      <h3>页数:${book.pages}</h3>
      <hr />
    `;
    bookList.appendChild(bookItem);
  });
  console.log(myLibrary);
});

内容的提问来源于stack exchange,提问作者Joey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 18:06:02