JSON 1
本文中的唯一一項任務是關於訪問 JSON 資料並在您的頁面中使用它。有關一些母貓及其幼崽的 JSON 資料可在sample.json 中找到。JSON 以文字字串的形式載入到頁面中,並透過 displayCatInfo() 函式的 catString 引數提供。
要完成任務,請填寫 displayCatInfo() 函式中缺失的部分,以儲存
- 三個母貓的名字,用逗號分隔,儲存在
motherInfo變數中。 - 幼崽的總數,以及雄性和雌性的數量,儲存在
kittenInfo變數中。
這些變數的值隨後會列印到螢幕上的段落中。
一些提示/問題
- JSON 資料以文字形式提供在
displayCatInfo()函式中。您需要先將其解析為 JSON,然後才能從中獲取任何資料。 - 您可能會想使用一個外部迴圈來遍歷貓,並將它們的名字新增到
motherInfo變數字串中,再使用一個內部迴圈來遍歷所有幼崽,累加所有/雄性/雌性幼崽的總數,並將這些詳細資訊新增到kittenInfo變數字串中。 - 最後一個母貓的名字前面應該有一個“and”,後面應該有一個句號。您如何確保這可以工作,無論 JSON 中有多少隻貓?
- 為什麼
para1.textContent = motherInfo;和para2.textContent = kittenInfo;行在displayCatInfo()函式內部,而不是在指令碼的末尾?這與非同步程式碼有關。
js
const para1 = document.querySelector(".one");
const para2 = document.querySelector(".two");
let motherInfo = "The mother cats are called ";
let kittenInfo;
const requestURL =
"https://mdn.github.io/learning-area/javascript/oojs/tasks/json/sample.json";
fetch(requestURL)
.then((response) => response.text())
.then((text) => displayCatInfo(text));
// Don't edit the code above here!
function displayCatInfo(catString) {
let total = 0;
let male = 0;
// Add your code here
// Don't edit the code below here!
para1.textContent = motherInfo;
para2.textContent = kittenInfo;
}
點選此處顯示解決方案
你完成的 JavaScript 應該看起來像這樣
js
// ...
// Don't edit the code above here!
function displayCatInfo(catString) {
let total = 0;
let male = 0;
const cats = JSON.parse(catString);
for (let i = 0; i < cats.length; i++) {
for (const kitten of cats[i].kittens) {
total++;
if (kitten.gender === "m") {
male++;
}
}
if (i < cats.length - 1) {
motherInfo += `${cats[i].name}, `;
} else {
motherInfo += `and ${cats[i].name}.`;
}
}
kittenInfo = `There are ${total} kittens in total, ${male} males and ${
total - male
} females.`;
// Don't edit the code below here!
para1.textContent = motherInfo;
para2.textContent = kittenInfo;
}