处理基于函数的场景时出现问题

problem dealing with a function based scenario

提问人:Muhammad Yaseen 提问时间:11/3/2023 最后编辑:PointyMuhammad Yaseen 更新时间:11/3/2023 访问量:39

问:

我正在学习 javascript 的基础知识

我目前在函数章节中,不知道为什么我的代码不起作用,我什至与 chatGPT 进行了检查,它说我的代码看起来不错,应该按预期运行。

这是场景;

声明一个名为 checkIfHealthyColony 的函数。

该函数应采用两个参数:

colony - 表示一个对象数组,每个对象代表一个单独的蚂蚁。每个 ant 对象都包含一个 name 属性和一个 type 属性。如果 ant 被感染,则 ant 对象的 type 属性将包含值 zombie

hasAntidote - 代表一个布尔值,它决定我们是否有解毒剂来消除感染!

如果没有蚂蚁是僵尸,或者 hasAntidote 为 true,我们的函数应该返回 true。否则,菌落的健康将受到损害,函数应返回 false。

这是给出的示例数组;

const exampleColony = [
    {
        name: "anthony",
        type: "worker"
    },
    {
        name: "dec",
        type: "worker"
    },
    {
        name: "marie-antoinette",
        type: "queen"
    },
    {
        name: "adam",
        type: "zombie"
    }
];

这是我的代码;

function checkIfHealthyColony(colony, hasAntidote) {
  for (const ant of colony) {
    if (ant.type === 'worker' || hasAntidote === true) {
      return true; // The colony is healthy
    }
  }
  return false; // The colony is not healthy
}

这就是我得到的反馈; 2 传球 1 失败

当发现僵尸并且没有解毒剂时应返回 false

✕ AssertionError:预期为 true 等于 false

当发现僵尸但有解毒剂时应返回 true

✓  Well done!

当未找到僵尸时应返回 true

✓  Well done!

当我输入 colony.type 而不是 ant.type 时,第一个条件是正确的,但最后一个条件不正确,我的头爆炸了 HELP

javascript 函数 if-statement 布尔值

评论

0赞 Pointy 11/3/2023
您的代码根本不检查“僵尸”情况;它必须区分“女王”和“僵尸”。
1赞 Barmar 11/3/2023
如果任何蚂蚁都是工人,则函数返回 true,而不是如果所有蚂蚁都是工人。
0赞 Barmar 11/3/2023
无需检查循环中的解毒剂,它不会改变。首先检查一下。

答:

1赞 Barmar 11/3/2023 #1

如果任何蚂蚁是工人,则函数返回 true。但可能还有另一只蚂蚁是僵尸,或者它们都是蚁后和雄蜂,它不会检查这一点。你需要颠倒测试的感觉。

你应该在循环之外检查,因为它不依赖于蚂蚁。hasAntidote

function checkIfHealthyColony(colony, hasAntidote) {
  if (hasAntidote) {
    return true;
  }
  for (const ant of colony) {
    if (ant.type === 'zombie') {
      return false; // The colony is unhealthy
    }
  }
  return true;
}

还有一个内置的数组方法,可以为你执行循环。some()

function checkIfHealthyColony(colony, hasAntidote) {
  return hasAntidote || !colony.some(ant => ant.type == 'zombie');
}

console.log(checkIfHealthyColony(exampleColony, true));
console.log(checkIfHealthyColony(exampleColony, false));
console.log(checkIfHealthyColony(exampleColony2, false));
<script>
  const exampleColony = [{
      name: "anthony",
      type: "worker"
    },
    {
      name: "dec",
      type: "worker"
    },
    {
      name: "marie-antoinette",
      type: "queen"
    },
    {
      name: "adam",
      type: "zombie"
    }
  ];
  const exampleColony2 = [{
      name: "anthony",
      type: "worker"
    },
    {
      name: "dec",
      type: "worker"
    },
    {
      name: "marie-antoinette",
      type: "queen"
    },
    {
      name: "adam",
      type: "drone"
    }
  ];
</script>