JavaScript图书目录程序:用户输入无法修改数组内图书标题
解决图书目录编辑时标题无法更新的问题
你当前代码里修改标题的逻辑存在两个核心问题:
myArray[index].getTitle().replace(...)只是对getTitle()返回的字符串做替换,生成新字符串,但根本没修改Books实例里的Title属性,所以数组里的对象数据完全没变。- 就算修改了对象属性,也没同步更新
sessionStorage和页面的展示内容,导致页面和存储的数据都没变化。
另外,编辑事件里的for循环完全多余——你已经通过用户输入确定了要修改的索引,不需要遍历整个数组。
修复方案
1. 给Books类添加属性修改方法(规范封装)
给Books类新增setter方法,让属性修改更符合面向对象的封装逻辑:
let myArray = []; class Books { constructor(Title, Author, Genre, Review) { this.Title = Title this.Author = Author this.Genre = Genre this.Review = Review } // 获取方法保留 getTitle() { return this.Title } getAuthor() { return this.Author } getGenre() { return this.Genre } getReview() { return this.Review } // 添加修改方法 setTitle(newTitle) { this.Title = newTitle } setAuthor(newAuthor) { this.Author = newAuthor } setGenre(newGenre) { this.Genre = newGenre } setReview(newReview) { this.Review = newReview } }
2. 重写编辑按钮的事件逻辑
去掉冗余循环,直接修改目标对象属性,同步更新存储和页面:
document.getElementById("editBtn").addEventListener("click", function(event) { // 先判断是否有图书可编辑 if (myArray.length === 0) { alert("还没有添加任何图书"); return; } let userInput = Number(prompt(`请选择要编辑的条目序号(1 到 ${myArray.length})`)); // 校验输入合法性 if (isNaN(userInput) || userInput < 1 || userInput > myArray.length) { alert("输入的序号不合法,请重新输入"); return; } let index = userInput - 1; let userInput2 = prompt("请选择要修改的内容:\n标题\n作者\n分类\n书评"); if (!userInput2) return; // 用户取消操作 let toLower = userInput2.toLowerCase(); if (toLower === "标题" || toLower === "title") { let userInput3 = prompt("请输入新的标题:"); if (!userInput3) return; // 使用setter修改标题 myArray[index].setTitle(userInput3); // 也可以直接修改属性:myArray[index].Title = userInput3; // 同步更新sessionStorage sessionStorage.setItem("array", JSON.stringify(myArray)); // 格式化渲染页面内容,更易读 document.getElementById("display").innerHTML = JSON.stringify(myArray, null, 2); console.log(myArray); } // 可按照同样逻辑扩展作者、分类、书评的修改功能 })
3. 优化添加图书后的页面展示
原代码里直接把sessionStorage的内容塞到display里,可读性差,改成格式化后的JSON:
document.getElementById("addBttn").addEventListener("click", function(event) { event.preventDefault(); let userTitle = document.getElementById("title").value; let userAuthor = document.getElementById("author").value; let userGenre = document.getElementById("genre").value; let userReview = document.getElementById("reviews").value; const newObj = new Books(userTitle, userAuthor, userGenre, userReview); myArray.push(newObj) sessionStorage.setItem("array", JSON.stringify(myArray)); // 格式化展示 document.getElementById("display").innerHTML = JSON.stringify(myArray, null, 2) })
内容的提问来源于stack exchange,提问作者Jay
相关产品推荐
相关产品推荐

