从 JSON (javascript) 中提取数组元素
Extracting array elements from JSON (javascript)
我正在尝试处理从 API url 接收到的 JSON 数据(这是我第一次处理此类工作)
以下函数returns 一个 20 元素数组的承诺:
const articles = () => {
return fetch(url)
.then(res => res.json())
.then(post => post.articles);
};
控制台视图:
现在,我想从数组中提取元素 - 我试过类似的方法:
articles()[0].name
但这行不通,我不确定是否有其他方法可以解决这个问题?感谢你的帮助。谢谢
你的 articles
功能 returns 一个承诺。您必须消费 承诺 (more on MDN):
articles().then(articleArray => {
console.log(articleArray);
});
或在 async
function 内:
const articleArray = await articles();
console.log(articleArray);
旁注:您的 fetch
代码缺少 HTTP 成功检查(HTTP 失败不是拒绝)。到目前为止,您 不是唯一错过这张支票的人,以至于 I've written a post on my anemic blog about it。带支票:
const articles = () => {
return fetch(url)
.then(res => {
if (!res.ok) {
throw new Error("HTTP error " + res.status);
}
return res.json();
})
.then(post => post.articles);
};
我正在尝试处理从 API url 接收到的 JSON 数据(这是我第一次处理此类工作)
以下函数returns 一个 20 元素数组的承诺:
const articles = () => {
return fetch(url)
.then(res => res.json())
.then(post => post.articles);
};
控制台视图:
现在,我想从数组中提取元素 - 我试过类似的方法:
articles()[0].name
但这行不通,我不确定是否有其他方法可以解决这个问题?感谢你的帮助。谢谢
你的 articles
功能 returns 一个承诺。您必须消费 承诺 (more on MDN):
articles().then(articleArray => {
console.log(articleArray);
});
或在 async
function 内:
const articleArray = await articles();
console.log(articleArray);
旁注:您的 fetch
代码缺少 HTTP 成功检查(HTTP 失败不是拒绝)。到目前为止,您 不是唯一错过这张支票的人,以至于 I've written a post on my anemic blog about it。带支票:
const articles = () => {
return fetch(url)
.then(res => {
if (!res.ok) {
throw new Error("HTTP error " + res.status);
}
return res.json();
})
.then(post => post.articles);
};