我在从数组获取 JSON 数据时遇到问题。
我尝试打印数组数据,但它不起作用:
<div id='asd'>lalala</div>
<button onclick='myfunction()'>click me</button>
<script>
function myfunction(){
var arr = [];
fetch('https://api.blockchair.com/bitcoin-sv/blocks?a=month,median(transaction_count)')
.then(response => response.json())
.then(result => arr.push(result));
console.log(arr)
document.getElementById('asd').innerHTML = arr[0]
}
</script>
我收到“未定义错误”。
最佳答案
您的问题是:
console.log(arr)
document.getElementById('asd').innerHTML=arr[0];
超出了你的期末考试.then
,这意味着它将在您的代码首次执行时运行,而不是在您的方法收到其结果之后运行。相反,您需要将其放入最终的 .then
中回调,以便它首先填充您的数组,然后输出结果:
function myfunction(){
var arr = [];
fetch('https://api.blockchair.com/bitcoin-sv/blocks?a=month,median(transaction_count)')
.then(response => response.json())
.then(result => {
arr.push(result);
console.log(arr);
document.getElementById('asd').innerHTML = JSON.stringify(arr[0]);
});
}
此外,如果要将输出添加到 DOM,则需要 .stringify
以便数据能够正常显示。
关于javascript - 如何从 JSON 数组中获取特定数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54359484/