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

使用Object构造函数创建对象存入数组时旧值被替换为undefined问题求解

问题修复方案

核心错误原因

  • 变量被错误重写:全局定义的Book、Author、Year三个变量原本存储的是DOM元素对象,第一次点击按钮时被直接重赋值为输入框的value字符串。第二次点击时,这三个变量已经是字符串类型,不存在.value属性,读取.value就会返回undefined。
  • 数组每次点击被重置:myLibrary数组定义在点击事件回调函数内部,每次触发点击都会创建新的空数组,之前添加的对象无法被保留。
  • 构造函数和添加方法重复声明:每次点击都会重复声明newBook构造函数和addBookToLibrary方法,属于不必要的性能损耗。

修复后代码

// 全局存储DOM元素和数组,避免被重写/重置
const bookInput = document.querySelector("#one");
const authorInput = document.querySelector("#two");
const yearInput = document.querySelector("#three");
const Btn = document.querySelector("button");
const myLibrary = [];

// 构造函数移到全局,符合首字母大写的命名规范
function NewBook(name, author, year) {
  this.name = name;
  this.author = author;
  this.year = year;
}

function addBookToLibrary(book, author, year) {
  const books = new NewBook(book, author, year);
  myLibrary.push(books);
}

Btn.addEventListener("click", () => {
  // 每次点击仅读取最新输入值,不修改存储DOM的原始变量
  const bookVal = bookInput.value;
  const authorVal = authorInput.value;
  const yearVal = yearInput.value;
  
  addBookToLibrary(bookVal, authorVal, yearVal);
  console.log(myLibrary);
  // 可选:添加完成后清空输入框
  bookInput.value = '';
  authorInput.value = '';
  yearInput.value = '';
});

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

相关产品推荐
方舟 Agent Plan

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

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