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

如何解决搜索输入过短时出现的Cannot read properties of undefined(reading 'forEach')报错

解决"Cannot read properties of undefined (reading 'forEach')"错误

你遇到的问题核心是:当接口返回Response: 'False'时,响应对象里没有Search数组,直接调用response.Search.forEach自然会触发"读取undefined的forEach属性"错误。以下是几种简单有效的修复方式:

方式一:增加前置校验

在执行forEach之前,先确认response.Search存在且是数组,同时保留原有的response.Response判断:

if(response.Response && response.Search && Array.isArray(response.Search)) {
  $('#list').html('');
  response.Search.forEach(function(movie) {        
    var movieContent;
    if(movie.Poster === 'N/A') {
      movieContent = `<li class="list-group-item">${movie.Title} - ${movie.Year}</li>`;
    } else {
      movieContent = `<li class="list-group-item">${movie.Title} - ${movie.Year} <a href="${movie.Poster}" class="btn btn-xs btn-primary" id="poster-link">Poster</a></li>`;
    }
    $('#list').append(movieContent).hide().fadeIn(); 
  });
}
// 可额外添加错误提示分支,优化用户体验
else {
  $('#list').html('<li class="list-group-item">搜索字符不能少于3个,请重新输入</li>');
}

方式二:使用可选链+空值合并运算符

如果你的运行环境支持ES2020及以上语法,可以用更简洁的写法,给response.Search设置空数组作为默认值:

if(response.Response) {
  $('#list').html('');
  // 若response.Search不存在,自动用空数组替代,forEach不会报错
  (response.Search ?? []).forEach(function(movie) {        
    var movieContent;
    if(movie.Poster === 'N/A') {
      movieContent = `<li class="list-group-item">${movie.Title} - ${movie.Year}</li>`;
    } else {
      movieContent = `<li class="list-group-item">${movie.Title} - ${movie.Year} <a href="${movie.Poster}" class="btn btn-xs btn-primary" id="poster-link">Poster</a></li>`;
    }
    $('#list').append(movieContent).hide().fadeIn(); 
  });
}

两种方式都能避免报错,第一种兼容性更好(适配旧运行环境),第二种写法更简洁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 21:15:42