【发布时间】:2018-03-11 14:11:59
【问题描述】:
我正在尝试制作一个简单的新闻提要应用来练习使用 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"
}
【问题讨论】:
-
嗯,JSON 让我有点困惑。
"articles"数组在哪里终止?如果您只想遍历数组,Sean Denny 的答案是使用art.author、art.title等来访问数据。或者,如果您想遍历这一切,您可以使用Object.keys().您可以通过在fetch()中以编程方式设置元素来将数据显示到 HTML 中
标签: javascript arrays json loops