假设我的JSON数组如下所示:
[{
"type": "Sweatshirt",
"brand": "H&M",
"Color": "Yellow",
"Neck": "Turtle neck",
"Arm": "Full Arm"
},
{
"type": "Sweatshirt",
"brand": "PUMA",
"Color": "Black",
"Neck": "Round neck",
"Arm": "Full Arm"
},
{
"type": "Dresses",
"Length": "knee length",
"Occasion": "Party",
"Neck": "Halter neck"
},
{
"type": "Dresses",
"Length": "Floor length",
"Occasion": "Casual",
"Neck": "Boat neck"
}
]
我如何在数组上循环,检查type
是连衣裙还是毛衣,并在HTMLdiv
中显示各自的值
以下是一个示例,它将向您展示如何循环并将值分配给html元素
此示例仅用于演示
array=[{ "type": "Sweatshirt", "brand": "H&M", "Color": "Yellow", "Neck": "Turtle neck", "Arm": "Full Arm" }, { "type": "Sweatshirt", "brand": "PUMA", "Color": "Black", "Neck": "Round neck", "Arm": "Full Arm" }, { "type": "Dresses", "Length": "knee length", "Occasion": "Party", "Neck": "Halter neck" }, { "type": "Dresses", "Length": "Floor length", "Occasion": "Casual", "Neck": "Boat neck" }]
disp=document.getElementById("disp")
array.forEach(o=>{
if(o.type=="Sweatshirt"){
type=document.createElement("li")
brand=document.createElement("li")
type.textContent=o.type
brand.textContent=o.brand
disp.appendChild(type)
disp.appendChild(brand)
}})
<div id="disp7"><ul id="disp"></ul></div>