首页 > 解决方案 > JavaScript在变量中获取API JSON数据?

问题描述

JS新手在这里。我想将来自 API 调用的 JSON 数据存储在我的 .fetch 方法中的变量中。

这是我当前的代码:

// Store database to array
let database = []

fetch('./database.json')
.then(response => response.json())
.then(data => console.log(data))

数据已成功记录在控制台中,但我希望将它们保存在数据库数组中。

知道我会怎么做吗?非常感谢大家!

标签: javascriptapifetch

解决方案


当然,将您的代码更改为以下内容:

// Store database to array
let database = []

fetch('./database.json')
.then(response => response.json())
.then(data => {
    database.push(data)
    console.log(database)
})

我希望这能解决你的问题。


推荐阅读