You need to enable JavaScript to run this app. JavaScript数组练习:searchForWaldo函数未通过测试的问题排查
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript数组练习:searchForWaldo函数未通过测试的问题排查

JavaScript 基础练习:Waldo 查找逻辑实现问题

练习要求说明

练习六(已完成)

判断传入的arrayOfNames数组是否包含全小写的"waldo",存在返回true,不存在返回false,当前containsWaldo函数已通过全部测试。

练习七(未通过)

基于已有的containsWaldo实现searchForWaldo函数:

  • 数组包含waldo时,返回I found waldo!
  • 数组不包含waldo时,返回I couldn't find waldo...
  • 禁止重复编写查找逻辑,直接复用containsWaldo

现有代码

console.log("练习六");
// - 判断arrayOfNames数组是否包含全小写"waldo"
// - 存在返回true,不存在返回false
// - 提示:直接调用已实现的contains函数,传入数组和"waldo"返回结果即可

function containsWaldo(arrayOfNames) {
  return contains(arrayOfNames, "waldo");
}

// 练习六测试
console.log("-----练习六测试-----");
console.log("* 数组含waldo时返回true");
console.log(containsWaldo(["bob", "nancy", "john", "shawnie", "waldo", "shaquon", "julie"]) === true);
console.log("* 数组不含waldo时返回false");
console.log(containsWaldo(["bob", "nancy", "john", "shawnie", "shaquon", "julie"]) === false);


// ----------------------------------------------------------------------------------------------
console.log("练习七");
// - 含waldo返回"I found waldo!",不含返回"I couldn't find waldo..."
// - 提示:直接调用containsWaldo获取判断结果,不要重复写查找逻辑

// 你当前的实现
function searchForWaldo(arrayOfNames) {
  return containsWaldo(arrayOfNames);
}

// 练习七测试
console.log("-----练习七测试-----");
console.log("* 数组含waldo时返回对应字符串");
console.log(searchForWaldo(["bob", "nancy", "john", "shawnie", "waldo", "shaquon", "julie"]) === "I found waldo!");
console.log("* 数组不含waldo时返回对应字符串");
console.log(searchForWaldo(["bob", "nancy", "john", "shawnie", "shaquon", "julie"]) === "I couldn't find waldo...");

问题原因

  1. 你当前的searchForWaldo直接返回了containsWaldo的布尔值,没有根据判断结果返回题目要求的提示字符串,导致测试用例的字符串匹配完全失败。
  2. 若出现"arrayOfNames" is not defined报错,是因为你之前的实现中直接引用了未在函数作用域/全局作用域定义的全局变量arrayOfNames,没有把测试用例的数组作为参数传入函数。

正确实现

function searchForWaldo(arrayOfNames) {
  // 复用已有逻辑获取判断结果
  const hasWaldo = containsWaldo(arrayOfNames);
  // 根据结果返回要求的字符串
  return hasWaldo ? "I found waldo!" : "I couldn't find waldo...";
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.26 14:36:03