如何用JavaScript实现数组相邻元素依次比较并输出对应提示?
问题分析
你的原函数存在以下问题:
- 仅判断了数组前两个元素的情况,没有遍历所有相邻元素对
- 返回值中的
n(i)未替换为实际的索引值 - 函数在第一次
return后就终止,无法处理后续元素的比较逻辑
解决方案
根据你的需求,我们需要遍历数组的所有相邻元素对,按规则生成对应的提示信息。以下是两种实现方式:
方式1:返回所有比较结果的数组
这种方式会收集所有相邻元素对的提示信息,最终返回一个结果数组:
function warnTheSheep(animals) { const results = []; // 处理第一个元素是狼的情况 if (animals[0] === "wolf") { results.push("Hey wolf go away!!"); return results; } // 遍历所有相邻元素对 for (let i = 0; i < animals.length - 1; i++) { const nextAnimal = animals[i + 1]; if (nextAnimal === "wolf") { results.push(`Hey sheep n${i}: you are going to be eaten!`); } else if (nextAnimal === "sheep") { results.push(`Hey sheep n${i}: Hello how are you?`); } } return results; } // 测试用例 console.log(warnTheSheep(["sheep", "wolf", "wolf", "sheep"])); // 输出: ["Hey sheep n0: you are going to be eaten!", "Hey sheep n1: Hello how are you?", "Hey sheep n2: you are going to be eaten!"]
方式2:逐个输出比较结果(直接打印)
如果你的需求是直接输出每个比较的结果,而不是返回数组,可以用这种方式:
function warnTheSheep(animals) { // 处理第一个元素是狼的情况 if (animals[0] === "wolf") { console.log("Hey wolf go away!!"); return; } // 遍历所有相邻元素对并打印结果 for (let i = 0; i < animals.length - 1; i++) { const nextAnimal = animals[i + 1]; if (nextAnimal === "wolf") { console.log(`Hey sheep n${i}: you are going to be eaten!`); } else if (nextAnimal === "sheep") { console.log(`Hey sheep n${i}: Hello how are you?`); } } } // 测试用例 warnTheSheep(["sheep", "wolf", "wolf", "sheep"]); // 输出: // Hey sheep n0: you are going to be eaten! // Hey sheep n1: Hello how are you? // Hey sheep n2: you are going to be eaten!
关键改进点
- 使用
for循环遍历所有相邻元素对(i从0到animals.length-2,确保i+1不越界) - 动态替换提示中的索引值
n${i},确保每个提示对应正确的羊的序号 - 区分“第一个元素是狼”的特殊情况,优先处理
- 针对不同的相邻元素组合,生成对应的提示信息
内容的提问来源于stack exchange,提问作者Vincenzo Chiovaro
相关产品推荐
相关产品推荐

