這是我第一次使用 API。我在下面粘貼了我的代碼,并附上了一些關于我試圖用它實作什么的評論,以及我在此程序中的小測驗是否有效。
第一部分是我應該做的。后半部分是我實施的一項測驗,以查看我的回圈 顯示邏輯是否有問題。這似乎不是問題。我的作業理論是,我在某些時候無法“移交”我獲取的資料。
你能發現我做錯了什么或忘記了什么嗎?
async function getCatalog() {
//storing response
let response = await fetch(apiURL); // stars a GET request (default)
// Storing data in form of JSON
const catalog = await response.json();
console.log(catalog, typeof catalog); // TESTS: these work. I recieve the expected information
if (response) {
//return catalog; // I'm not sure if I need this or not to make displayCatalog work.
displayCatalog();
}
}
//calling async function
getCatalog();
//TEST
document.getElementById('items').style.border = '1px dashed blue';
// this is the target element in my HTML where I want to display my results. I gave it a border to be able to see it while I work.
// function to define innerHTML
function displayCatalog() {
//Here I am trying to loop through the objects in my response to display some of the information. Before I focus on displaying the right info correctly, I'm trying to display ANY of it.
for (let item of catalog) {
let newDiv = document.createElement('div');
let newContent = `Hello I'm ${item.name}`;
newDiv.innerHTML = newContent;
newDiv.style.border = '2px dashed red';
document.getElementById('items').appendChild(newDiv);
}
}
// NO API TEST
// Here I created an array with a few objects in it to loop through it and see if my logic is sound there. It does work. It displays what I expect it to.
let objArray = [
{
name: 'Dean',
species: 'Human(ish)',
eyecolor: 'Green',
car: 'Baby, duh',
},
{
name: 'Sam',
species: 'Human',
eyecolor: 'Hazel',
status: 'Alive',
car: 'green',
},
{
name: 'Castiel',
species: 'Human(ish)',
eyecolor: 'Blue',
bonded: 'yes',
car: 'black',
},
];
let attempt;
for (let item of objArray) {
let Bap = document.createElement('div');
attempt = `Hi, my name is ${item.name}, my car is ${item.car}.`;
Bap.innerHTML = attempt;
Bap.style.border = '1px dashed green';
document.getElementById('items').appendChild(Bap);
}```
uj5u.com熱心網友回復:
問題是您在catalog內部定義getCatalog并嘗試在內部使用它displayCatalog(未定義的地方)
相反,你應該這樣做
function displayCatalog(catalog){
...
}
并在呼叫函式時傳遞目錄
async function getCatalog() {
let response = await fetch(apiURL); // stars a GET request (default)
const catalog = await response.json();
if (response) {
displayCatalog(catalog);
}
}
uj5u.com熱心網友回復:
我相信catalog它是 getCatalog 函式的區域變數,因此不能在 displayCatalog 函式中使用。
您可以在呼叫函式時將其作為引數傳入:
async function getCatalog() {
...
if (response) {
displayCatalog(catalog);
}
}
function displayCatalog(catalog) {
...
//the variable catalog is now accessible
}
或者,如果您在函式定義中呼叫了引數目錄,displayCatalog()例如function displayCatalog(info)它現在可以作為區域變數資訊訪問。
請注意,從 getCatalog 回傳目錄將終止該函式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/486579.html
標籤:javascript 获取 API 循环
上一篇:我如何映射我的詞典(一個元素)
下一篇:如何在按鍵上選擇輸入標簽
