技能测试:JSON

本次技能测试旨在帮助您评估是否理解了我们的处理 JSON 文章。

注意: 如需帮助,请阅读我们的“技能测试”使用指南。您也可以通过我们的沟通渠道与我们联系。

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;
}