我需要创建一个类似
的列表响应位于带有某些节点的.TXT文件中
{
"pets":[
{ "animal":"animal 1", "name":"Fido" },
{ "animal":"animal 2", "name":"Felix" },
{ "animal":"animal 3", "name":"Lightning" }
]
}
如何创建JS以在DIV中返回动物的名字?
答案 0 :(得分:0)
可能有比我更好的方法,但这是有的。
您可以使用for loop
遍历对象,如下所示:
const response = {
"pets": [{
"animal": "animal 1",
"name": "Fido"
},
{
"animal": "animal 2",
"name": "Felix"
},
{
"animal": "animal 3",
"name": "Lightning"
}
]
};
// Loop through the pets property of the response object
for (let i = 0; i < response.pets.length; i++) {
// Add the name property of the pets property to the div
document.getElementById('animals').innerHTML += `${response.pets[i].name} <br>`;
}
<div id="animals"></div>
答案 1 :(得分:0)
检查以下代码。希望对您有所帮助:)
let response = {
"pets": [{
"animal": "animal 1",
"name": "Fido"
},
{
"animal": "animal 2",
"name": "Felix"
},
{
"animal": "animal 3",
"name": "Lightning"
}
]
}
function getAnimals() {
let html = '';
response.pets.forEach(animal => {
html += `<div>${animal.name}</div>`;
});
console.log(html)
}
getAnimals();