求助:排查Uncaught TypeError: Cannot read properties of undefined (reading 'brand')错误
错误原因与解决方法:Uncaught TypeError: Cannot read properties of undefined (reading 'brand')
错误原因
- 循环边界越界:数组
bikes的长度为1,合法索引仅为0。你的循环条件写为i <= bikes.length,当循环执行到i = 1时,bikes[1]不存在(值为undefined),尝试读取undefined的brand属性就会触发该类型错误。 - 冗余函数定义:
createBikes函数被定义在循环内部,每次循环都会重新创建这个函数,既浪费性能,也不符合代码组织规范。
解决方法
1. 修正循环边界
将循环条件从i <= bikes.length改为i < bikes.length,确保索引始终在数组的合法范围内。
2. 优化函数结构
将createBikes函数移到循环外部,避免重复创建,并通过参数传递需要插入的HTML内容,提升代码复用性。
修正后的完整代码
const bikes = [ { brand: "Specialized", name: `Specialized STUMPJUMPER EVO - 29" Carbon Mountainbike - cast battleship`, price: "5.461,34 €", image: "../img/mtb/Stumpjumper.jpg", }, ]; // 提取函数到循环外部 function createBikes(bikeElement) { document .getElementById("container") .insertAdjacentHTML("beforeend", bikeElement); } // 修正循环条件 for (let i = 0; i < bikes.length; i++) { let bikeElement = ` <div class="card"> <p class="brand">${bikes[i].brand}</p> </div>`; createBikes(bikeElement); }
更简洁的写法(使用forEach)
如果你想避免手动处理索引,可以使用数组的forEach方法,代码更直观且不易出错:
const bikes = [ { brand: "Specialized", name: `Specialized STUMPJUMPER EVO - 29" Carbon Mountainbike - cast battleship`, price: "5.461,34 €", image: "../img/mtb/Stumpjumper.jpg", }, ]; function createBikes(bikeElement) { document.getElementById("container").insertAdjacentHTML("beforeend", bikeElement); } // forEach自动遍历数组元素,无需手动管理索引 bikes.forEach(bike => { let bikeElement = ` <div class="card"> <p class="brand">${bike.brand}</p> </div>`; createBikes(bikeElement); });
内容的提问来源于stack exchange,提问作者Bulat
相关产品推荐
相关产品推荐

