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

使用Array与条件语句实现JS交通信号灯功能的问题排查

问题分析与解决方案

你的代码无法实现预期效果的核心原因是:把signal变量定义成了包含三个颜色的数组,而不是存储单一信号灯状态的字符串。数组和字符串做相等判断永远不会成立,所以只会执行else分支的内容。

修正方案一:设置单一信号灯状态

直接将signal设为单个颜色字符串,就能匹配对应的条件分支:

// 可替换为"yellow"或"green"来测试不同状态
var signal = "red";

if (signal == "red") {
    console.log("Danger");
} else if (signal == "yellow") {
    console.log("Stop");
} else {
    console.log("Cross the road");
}

修正方案二:遍历所有状态测试(可选)

如果需要一次性测试三种信号灯状态的输出,可以用循环遍历数组中的每个值:

var signals = ["green", "yellow", "red"];

for (var signal of signals) {
    if (signal == "red") {
        console.log("Danger");
    } else if (signal == "yellow") {
        console.log("Stop");
    } else {
        console.log("Cross the road");
    }
}

内容的提问来源于stack exchange,提问作者Mohammad Nadim Mahmud Neon

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 15:07:50