我是新來的,我正在學習JS!特別是 JSON!但是,我遇到了一個我無法解決的練習,也是因為我不明白我做錯了什么。我需要從 StarWars API 中提取有關行星的資訊。所以我進行了經典的提取,結果我以 JSON 的形式獲得了關于地球的一般資訊。但是,我必須提取行星名稱并且卡住了,因為當我檢查 PlanetsData 變數時,它給了我未定義的資訊。因此,我為提取行星名稱而撰寫的回圈由于某種原因不起作用。所以,我的問題是:
- 為什么我得到 PlanetsData 變數的“未定義”?.. 我不應該得到在控制臺中正確顯示的 JSON 嗎?
- 我是否正確撰寫了回圈?謝謝誰來回答我!
這是我的代碼:
async function getPlanetsData() {
const planetsData = await fetch ("https://swapi.dev/api/planets").then(data => {
return data.json()}).then(planets => {console.log(planets.results)}) // ---> Here i receive the JSON data
for (let key in planetsData) {
const someInfo = planetsData.results[key].name
console.log(JSON.stringify(someInfo)) } // ---> I don't understand why, but I don't get anything here. There is no response in the console, as if the call did not exist
}
getPlanetsData()
uj5u.com熱心網友回復:
您可以以不同且更清晰的方式撰寫相同的函式,查看注釋以理解代碼!
async function getPlanetsData() {
// 1. Fetch and wait for the response
const response = await fetch ("https://swapi.dev/api/planets");
// 2. Handle the response, in that case we return a JSON
// the variable planetsData now have the whole response
const planetsData = await response.json();
// console.log(planetsData); // this will print the whole object
// 3. Return the actual data to the callback
return planetsData;
}
// Function usage
// 4. Call "getPlantesData" function, when it completes we can call ".then()" handler with the "planetsData" that contains your information
getPlanetsData().then(planetsData => {
// 5. Do whatever you want with your JSON object
// in that case I choose to print every planet name
var results = planetsData.results; // result array of the object
results.forEach(result => console.log(result.name));
});
uj5u.com熱心網友回復:
您似乎遇到了與以下相同的問題:讀取檔案內容并將其保存到全域變數中
告訴我們它是否能解決您的問題。
(更新)
明確回答您的問題。
- 第一個問題:
要將價值轉化為可變行星資料,您只有一個選擇
async function getPlanetsData() {
const response = await fetch ("https://swapi.dev/api/planets")
const planetsData = await response.json()
for (let key in planetsData) {
const someInfo = planetsData.results[key].name
console.log(JSON.stringify(someInfo))
}
}
getPlanetsData()
第二種選擇是可能的,但不直觀。僅當獲取完成時,planetsData 才會有價值。您的 for 回圈將在您的 fetch 完成之前執行,因此在 planetsData 獲得值之前
function getPlanetsData() {
let planetsData;
fetch("https://swapi.dev/api/planets")
.then((data) => {
return data.json();
})
.then((planets) => {
planetsData = planets;
});
for (let key in planetsData) { // /!\ planetsData can be undefined
const someInfo = planetsData.results[key].name
console.log(JSON.stringify(someInfo))
}
}
getPlanetsData();
- 第二個問題:
您沒有正確撰寫回圈。要解決 Promise,最好在使用 await 和之間進行選擇。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/513973.html
