无法读取未定义的属性(读取"品牌")



在创建这个短脚本时,我遇到了这个错误Uncaught TypeError: Cannot read properties of undefined (reading 'brand')。下面是我写的代码。p class="brand">${bikes[i].brand}

const bikes = [
{
brand: "Specialized",
name: `Specialized STUMPJUMPER EVO - 29" Carbon Mountainbike - cast battleship`,
price: "5.461,34 €",
image: "../img/mtb/Stumpjumper.jpg",
},
];
for (let i = 0; i <= bikes.length; i++) {
let bikeElement = `
<div class="card">
<p class="brand">${bikes[i].brand}</p>
</div>`;
createBikes();
function createBikes() {
document
.getElementById("container")
.insertAdjacentHTML("beforeend", bikeElement);
}
}

您需要切换您的for循环使用<而不是<=。数组的长度是1。如果是i == 1,它将无法找到array[1]项,因为数组是从0开始索引的。

const bikes = [
{
brand: "Specialized",
name: `Specialized STUMPJUMPER EVO - 29" Carbon Mountainbike - cast battleship`,
price: "5.461,34 €",
image: "../img/mtb/Stumpjumper.jpg",
},
];
for (let i = 0; i < bikes.length; i++) {
let bikeElement = `
<div class="card">
<p class="brand">${bikes[i].brand}</p>
</div>`;
createBikes();
function createBikes() {
document
.getElementById("container")
.insertAdjacentHTML("beforeend", bikeElement);
}
}
<div id="container"></div>

最新更新