API返回JSON对象,结果为数组,如何迭代它们?

问题描述 投票:0回答:1

我正在尝试制作一个简单的新闻Feed应用程序来练习使用API​​。我已经提出了获取请求,但我无法确定如何正确迭代数组。我的目标只是为了能够获取作者和标题并将其输出到html中的页面

使用Javascript

var url = 'https://newsapi.org/v2/top-headlines?' +
      'country=us&' +
      'apiKey=123DemoKey';
var req = new Request(url);
fetch(req)
    .then(function(response) {
        console.log(response.json());
    })

来自API的返回数据片段

{
"status": "ok",
"totalResults": 20,
-"articles": [
-{
-"source": {
"id": "cnn",
"name": "CNN"
},
"author": "Sheena McKenzie, CNN",
"title": "Russian spy attack: Customers urged to wash clothes as traces of nerve agent found",
"description": "Customers at a restaurant and pub in Salisbury were urged to wash their clothes Sunday, after traces of the nerve agent used on Russian spy Sergei Skripal and his daughter were detected.",
"url": "https://www.cnn.com/2018/03/11/europe/russian-spy-attack-customers-told-to-wash-clothes-intl/index.html",
"urlToImage": "https://cdn.cnn.com/cnnnext/dam/assets/180306183502-russian-spy-critically-ill-salisbury-uk-investigation-black-pkg-00005819-super-tease.jpg",
"publishedAt": "2018-03-11T13:07:01Z"
}
javascript arrays json loops
1个回答
0
投票

由于News API返回JSON,您可以像对待它一样解析它,然后使用.forEachfor...of循环来迭代结果。

fetch('https://newsapi.org/v2/top-headlines')
.then(r => r.json())
.then(r => {
    r.articles.forEach(art => {
        // ... do something with `art`
    });

    for (const art of r.articles) {
        // ... do something with `art`
    }
});
© www.soinside.com 2019 - 2024. All rights reserved.