如何使用Javascript循环获取和显示JSON文件中的特定索引
我目前正在使用fetch-in javascript从另一个站点获取信息,并将其保存到我自己的站点中。我遇到的问题是,我使用循环将JSON文件的所有索引显示到我的站点中。实际上,我想要得到具体的索引来显示,而不是全部,例如,索引2、4和6 以下是我目前的代码:如何使用Javascript循环获取和显示JSON文件中的特定索引,javascript,arrays,json,loops,fetch,Javascript,Arrays,Json,Loops,Fetch,我目前正在使用fetch-in javascript从另一个站点获取信息,并将其保存到我自己的站点中。我遇到的问题是,我使用循环将JSON文件的所有索引显示到我的站点中。实际上,我想要得到具体的索引来显示,而不是全部,例如,索引2、4和6 以下是我目前的代码: window.addEventListener("load", (event)=>{ const requestURL = 'https://byui-cit230.github.io/weather/data
window.addEventListener("load", (event)=>{
const requestURL = 'https://byui-cit230.github.io/weather/data/towndata.json';
fetch(requestURL)
.then(function (response) {
return response.json();
})
.then(function (jsonObject) {
const towns = jsonObject['towns'];
for (let i = 0; i < towns.length; i++ ) {
let towninfo = document.createElement('section');
let townname = document.createElement('h2');
townname.textContent = towns[i].name;
towninfo.appendChild(townname);
document.querySelector('div.weathertowns').appendChild(towninfo);
}
});
})
window.addEventListener(“加载”,(事件)=>{
常量请求URL=https://byui-cit230.github.io/weather/data/towndata.json';
获取(请求URL)
.然后(功能(响应){
返回response.json();
})
.then(函数(jsonObject){
const towns=jsonObject['towns'];
for(设i=0;i
这将显示参考中的所有城镇,但我只想显示3个特定城镇的标题。关于如何进行这项工作有什么建议吗?类似的建议
window.addEventListener(“加载”,(事件)=>
{
常量请求URL=https://byui-cit230.github.io/weather/data/towndata.json'
,divWeathertowns=document.querySelector('div.weathertowns')
;
获取(请求URL)
.then(response=>response.json())
.然后(jsonObject=>
{
const towns=jsonObject['towns']
;
for(设i为[2,4,6])
{
让towninfo=document.createElement('section')
,townname=document.createElement('h2')
;
townname.textContent=towns[i].name;
towninfo.appendChild(townname);
附件儿童(towninfo);
}
});
})