javascript - 如何从 JSON 数组中获取特定数据?

标签 javascript json

我在从数组获取 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/

相关文章:

javascript - onClick 在表单内不起作用?

javascript - Ember.js:对模型进行分组(使用 ArrayProxy)

android - 如何使座位布局像redbus?

ios - Swift缓存tableview json数据

javascript - 如何制作动态名称选择器(无限)

javascript - 客户端 JavaScript 和/或 JavaScript 代码使用 jquery 调用 WCF 服务检索 System.IO.Stream 的集合?

javascript - 无法在 Ionic 3 中链式 promise

使用多维数组的 JavaScript 多级排序

c# - 如何在 JSON.NET 中组合/合并两个 JArray

c# - 使用 C# 和 Json.Net 进行解析