Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/437.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用Javascript循环获取和显示JSON文件中的特定索引_Javascript_Arrays_Json_Loops_Fetch - Fatal编程技术网

如何使用Javascript循环获取和显示JSON文件中的特定索引

如何使用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

我目前正在使用fetch-in javascript从另一个站点获取信息,并将其保存到我自己的站点中。我遇到的问题是,我使用循环将JSON文件的所有索引显示到我的站点中。实际上,我想要得到具体的索引来显示,而不是全部,例如,索引2、4和6

以下是我目前的代码:


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);
}
});
})