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

JavaScript实现书籍对象数组标题搜索功能运行异常问题求助

代码存在的核心问题

  • 字符串转小写的方法调用错误:toLowerCase是字符串的内置方法,必须加括号()执行才能得到转小写后的字符串结果。你代码里直接写.toLowerCase实际是在比较函数本身,两个不同的函数对象恒不相等,所以匹配永远失败,这是代码不生效的核心原因。
  • 循环变量i未显式声明:循环里直接写i = 0会将i泄漏为全局变量,存在变量污染风险,应该用let声明块级作用域的循环变量。
  • 冗余全局变量:全局声明的found变量完全可以封装在函数内部,没必要占用全局命名空间。

修复后可直接运行的代码

let book = {
  title: "The 48 Laws of Power",
  author: "Robert Greene",
  numOfPages: 452,
  publisher: "Penguin Books",
  rating: "4.5 stars"
}

let book2 = {
  title: "How to Catch a Turkey",
  author: "Adam Wallace",
  numOfPages: 40,
  publisher: "",
  rating: "5 stars"
}

let book3 = {
  title: "Glitter Every Day: 365 Quotes from Women I Love",
  author: "Andy Cohen",
  numOfPages: 384,
  publisher: "Henry Holt and Co.",
  rating: "3 stars"
}

let bookArr = [book, book2, book3];
let searchBtn = document.getElementById('search-button');

let bookSearch = function() {
  let input = document.getElementById('book-search');
  // 提前处理搜索关键词:去空格+转小写,避免循环内重复处理
  const searchKey = input.value.trim().toLowerCase();
  let foundBook = null;
  for (let i = 0; i < bookArr.length; i++) {
    if (searchKey === bookArr[i].title.toLowerCase()) {
      foundBook = bookArr[i];
      break;
    }
  }
  if (foundBook) {
    console.log(foundBook);
  } else {
    console.log("The book was not found.");
  }
}
searchBtn.addEventListener('click', bookSearch);

进阶优化建议

  • 用数组内置方法简化查找逻辑:不用手动写for循环,直接调用Array.find()方法可以直接返回匹配的元素,匹配失败返回undefined,代码更简洁易读,优化后核心逻辑可以缩减为:
    let bookSearch = function() {
      const searchKey = document.getElementById('book-search').value.trim().toLowerCase();
      const foundBook = bookArr.find(book => book.title.toLowerCase() === searchKey);
      console.log(foundBook || "The book was not found.");
    }
    
  • 支持模糊匹配:如果不需要完全一致的标题匹配,可以把判断逻辑改成book.title.toLowerCase().includes(searchKey),用户输入关键词片段就能匹配到对应书籍。
  • 增加输入校验:可以先判断搜索框为空时直接提示用户输入内容,不用执行无效的查找逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 03:06:03