JS中使用数组和条件的交通信号灯



我想建一个交通信号灯。

将有一个名为signal的变量,其中绿色,黄色和红色作为该变量的值存储。如果交通灯显示红灯,那就意味着有危险。如果交通灯显示黄灯,我应该停车。如果有绿灯,我可以过马路。

我的代码是:

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

我希望,如果我选择一种颜色,那么它将显示我之前提到的唯一输出

您的代码流程不正确,无法解决您的问题。

不需要检查数组值

你只需用if检查…其他条件。

// you can change value to get your results - "green", "yellow", "red"
var signal = "green"; 
if (signal == "red")
{console.log("Danger");
}
else if (signal == "yellow"){
console.log("Stop");
}else {
console.log("Cross the road");
}

您的变量signal的值为["green", "yellow", "red"],由于您从未更改过它,因此它永远不会是"red","yellow"或"green"。一个是字符串数组,而另一个只是字符串。

您的模型缺少一个部件,即当前信号。

var signals = ["green", "yellow", "red"];
var currentSignal = "red";
if (currentSignal === signals[2]) {
console.log("Danger");
}
else if (currentSignal === signals[1]) {
console.log("Stop");
}
else {
console.log("Cross the road");
}

但这有点难读,索引数组和东西。如果currentSignal被设置为"teal"呢?所以让我们把你的信号重构成某种枚举,或者只是一个普通的对象:

var signals = {
red: "red",
yellow: "yellow",
green: "green"
};
var currentSignal = signals.green;
if (currentSignal === signals.red) {
console.log("Danger");
}
else if (currentSignal === signals.yellow) {
console.log("Stop");
}
else {
console.log("Cross the road");
}

在一个简单的场景中,这就足够了,但从技术上讲,你仍然可以给currentSignal赋一个值,比如…"""black",因为javascript不能很好地处理类型,所以您可以(或应该)添加另一个条件:

var signals = {
red: "red",
yellow: "yellow",
green: "green"
};
var currentSignal = "3 double whoppers";
if (currentSignal === signals.red) {
console.log("Danger");
}
else if (currentSignal === signals.yellow) {
console.log("Stop");
}
else if (currentSignal === signals.green) {
console.log("Cross the road");
}
else {
throw new Error("invalid signal detected");
}

当然,根据你的喜好,你也可以使用一个switch语句:

switch(currentSignal) {
case signals.red:
console.log("Danger");
break;
case signals.yellow:
console.log("Stop");
break;
case signals.green:
console.log("Cross the road");
break;
default:
throw new Error("invalid signal detected");
}

相关内容

  • 没有找到相关文章

最新更新