You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用If语句和Boolean类型完成TDD测试,实现isRainbowColor函数

TDD实现彩虹颜色判断函数问题

需求说明

英语中彩虹的颜色通常按如下顺序排列:
red orange yellow green blue indigo violet
请声明一个名为isRainbowColor的函数,需支持大小写不敏感校验,即"red"、"Red"、"RED"、"ReD"、"rEd"都属于合法的彩虹颜色。

/**
@param {string} ??? - 待校验的颜色值 @returns {boolean} 入参是否为彩虹颜色 */

现有问题代码

function isRainbowColor(string){
  let rainbowColor = [];
  for (const string of rainbowColor){
    if (string != rainbowColor){
      return true;
}else{
      return false;
    }
  }
}

报错信息

错误信息

未通过的测试用例代码

actual = isRainbowColor("red");
expected = true;

if (actual === expected) {
  console.log("Test PASSED!");
} else {
  console.error("Test FAILED. Keep trying!");
  console.group("Result:");
  console.log("  actual:", actual);
  console.log("expected:", expected);
  console.groupEnd();
}

actual = isRainbowColor("rEd");
expected = true;

if (actual === expected) {
  console.log("Test PASSED!");
} else {
  console.error("Test FAILED. Keep trying!");
  console.group("Result:");
  console.log("  actual:", actual);
  console.log("expected:", expected);
  console.groupEnd();
}

actual = isRainbowColor("Brown");
expected = false;

if (actual === expected) {
  console.log("Test PASSED!");
} else {
  console.error("Test FAILED. Keep trying!");
  console.group("Result:");
  console.log("  actual:", actual);
  console.log("expected:", expected);
  console.groupEnd();
}

修正方案

原代码问题

  • 彩虹颜色数组为空,没有存储正确的7种彩虹色值
  • 循环变量和函数入参重名,会导致变量覆盖
  • 逻辑判断错误,把字符串和整个数组做对比,且循环内直接return会导致只判断第一个元素就结束
  • 没有处理大小写不敏感的需求

修正后代码

function isRainbowColor(color) {
  // 定义所有彩虹色,统一小写存储方便对比
  const rainbowColors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];
  // 入参转小写实现大小写不敏感校验
  const inputLower = color.toLowerCase();
  // 遍历匹配颜色
  for (const validColor of rainbowColors) {
    if (validColor === inputLower) {
      return true;
    }
  }
  // 无匹配返回false
  return false;
}

修正后代码可直接通过所有测试用例。


内容的提问来源于stack exchange,提问作者Serkan Toto

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 09:54:04