我正在使用fetch()命令以 JSON 格式獲取資料陣列。我正在使用函式fetchURL()以 JSON 格式獲取資料。我用async-await. 然后在收到的每個資料中,我試圖將它的login欄位添加到我在 HTML 檔案中創建的有序串列中。
我已經創建了一個createListItem()函式來在 HTML 檔案中查找有序串列標記并將其附加到該login欄位中。但首先我嘗試將所有login欄位存盤在一個陣列中arr。但我無法在其中存盤login欄位。
但是當我直接使用createListItem()函式創建一個帶有login " 欄位作為文本的串列項時,我可以將這些欄位添加到有序串列中,因此我得到了有序串列。我正在注釋掉讓我直接在瀏覽器上輸出的行當我不將login欄位存盤在以下視窗中時arr:
代碼:
function createListItem(text) {
const parent = document.getElementsByTagName("ol");
const entry = document.createElement("li");
entry.textContent = text;
parent[0].appendChild(entry);
}
const url = "https://api.github.com/users ";
async function fetchURL() {
return (await fetch(url)).json();
}
let arr = [];
async function createList() {
const data = await fetchURL();
for (let i = 0; i < data.length; i ) {
//createListItem(`${data[i].login}`);
arr.push(data[i].login);
}
}
createList();
uj5u.com熱心網友回復:
您正在獲取陣列中的資料,您需要在呼叫createList()函式后創建串列:
createList().then(function(){
arr.forEach(element => {
createListItem(element);
});
});
您還可以arr在createList函式中定義并回傳,那么您的代碼將是這樣的:
async function createList() {
let arr = [];
const data = await fetchURL();
for (let i = 0; i < data.length; i ) {
//createListItem(`${data[i].login}`);
arr.push(data[i].login);
}
return arr;
}
createList().then(arr=>{
arr.forEach(element => {
createListItem(element);
});
});
uj5u.com熱心網友回復:
您只需使用一個異步函式即可實作您的目標:
const url="http://jsonplaceholder.typicode.com/users";
async function getList(u){
const arr=(await fetch(u).then(r=>r.json())).map(e=>e.username);
document.querySelector("ol").innerHTML=arr.map(u=>`<li>${u}</li>`).join("");
console.log(arr);
}
getList(url);
<h2>List of login names</h2>
<ol></ol>
<p>end of page</p>
在上面的代碼片段中,我使用了 typicode.com 提供的公共資源并提取了 的屬性username而不是login。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/355797.html
標籤:javascript dom 异步等待 拿来
