【发布时间】:2022-01-14 23:03:00
【问题描述】:
数据源(JSON):
{
"photographers": [{
"name": "Mimi Keel",
"id": 243,
"city": "London",
"country": "UK",
"tags": ["portrait", "events", "travel", "animals"],
"tagline": "Voir le beau dans le quotidien",
"price": 400,
"portrait": "MimiKeel.jpg"
},
{
"name": "Ellie-Rose Wilkens",
"id": 930,
"city": "Paris",
"country": "France",
"tags": ["sports", "architecture"],
"tagline": "Capturer des compositions complexes",
"price": 250,
"portrait": "EllieRoseWilkens.jpg"
}
],
我正在尝试循环遍历第一个 photographers 条目中键 tags 中包含的数组,并在列表项中显示所有标签。
这是我目前得到的:
function fetchData() {
fetch("sample json file.json")
.then(response => response.json())
.then(data => {
console.log(data.photographers[0].tags[1])
// looping throw tags of a photographer
var output = "";
for (var i = 0; i <= data.photographers[0].tags.length; i++) {
for (keys in data.photographers[0].tags[i]) {
console.log(data.photographers[0].tags[i])
if (data.photographers[0].tags[i].hasOwnProperty(keys)) {
output += '<li>' +
'<a href="' + data.photographers[0].tags[i] +
'">' + data.photographers[0].tags[i] + '</a>' +
'</li>';
}
}
}
var update = document.getElementById('tags');
update.innerHTML = output;
})
}
fetchData();
我愿意接受任何建议或更正我的代码
【问题讨论】:
-
到底是什么问题?
-
你要求重构吗?因为这是错误的堆栈:在旁注中,您可以在第二个循环中将 `data.photographers[0].tags[i]` 替换为
key。 -
不要使用
for .. in迭代数组,而是使用正确的数组方法或for .. of。 -
当我尝试循环遍历标签并多次显示它们时
标签: javascript json frontend