2017-03-24 174 views
-1

如何将if语句转换为switch case?我想声明像这样的变量:将if语句转换为switch/case

myAge = parseFloat(prompt("Enter you age: ")); 

if(myAge <18) { 
    alert("You cant not vote at this " +myAge); 
} else if (myAge >18) { 
    alert("Vote wisely, you are " +myAge "years old!"); 
} else { 
    alert("Invalid age"); 
} 
+7

如果'myAge == 18'? –

+3

除了@JonathonReinhart所说的,你为什么要把它作为开关语句?当然你只有两条路可以遵循?更正的if语句对我来说似乎是合理的。 – Steve

+0

是的请我想包括,但也有点混乱。请帮助 –

回答

1

给条件,如果年龄< 18, 你不能不在这个年龄

投票,如果年龄> = 18,你可以在这个年龄段的投票。

否则无效年龄。

var myAge = parseFloat(prompt("Enter you age: ")); 
 
switch (true) { 
 
    case myAge < 18: 
 
    alert("You cant not vote at this " + myAge); 
 
    break; 
 

 
    case myAge >= 18: 
 
    alert("Vote wisely, you are " + myAge + " years old!"); 
 
    break; 
 

 
    default: 
 
    alert("Invalid age"); 
 
}

+0

非常感谢,它非常完美,我非常感谢。 –

1

回答你的“我怎样才能将其转换转”的问题,你可以实现一个功能,这使得C风格的比较,并返回-1,0或1作为比较的结果。

以下示例使用setInterval来模拟多个不同情况。
这仅用于示例。

function compareTo(a, b) { 
 
    if (a < b) 
 
    return -1; 
 

 
    if (a > b) 
 
    return 1; 
 

 
    return 0; 
 
} 
 

 

 
function EvaluateAge() { 
 
    // Generate a random age between 10 and 40 
 
    var myAge = Math.floor((Math.random() * 30) + 10); 
 
    switch (compareTo(myAge, 18)) { 
 
    case -1: 
 
     console.log(myAge, " less than 18"); 
 
     break; 
 

 
    case 0: 
 
     console.log(myAge, " equal to 18"); 
 
     break; 
 

 
    case 1: 
 
     console.log(myAge, "more than 18"); 
 
     break; 
 
    } 
 
} 
 

 
// Example only 
 
setInterval(EvaluateAge, 1000);

另一种方法是用JS switch能力交换条件使用true

var myAge = 16; 
 
switch (true) { 
 
    case myAge < 18: 
 
    console.log("less than 18"); 
 
    break; 
 

 
    case myAge === 18: 
 
    console.log("equal to 18"); 
 
    break; 
 

 
    case myAge > 18: 
 
    console.log("more than 18"); 
 
    break; 
 
}

但是,它不看起来不错,避免这种用法是个好主意。

其实,你的if看起来不错,你不需要将它转换为switch - 它不会增加你的代码的可读性/可维护性。

+0

我对你的例子做了一个小的补充,它增加了一个'interval',它模拟了switch语句的多个调用。如果您认为这是令人卷土重来的,请随时恢复。 – Zze

0

不知道为什么你会想,如果语句来做到这一点而不是简洁,但你可以像这样:

var myAge = parseFloat(prompt("Enter you age: ")); 
 
switch (true) { 
 
    case myAge < 18: 
 
    alert("You cant not vote at this " + myAge); 
 
    break; 
 

 
    case myAge > 18: 
 
    alert("Vote wisely, you are " + myAge + " years old!"); 
 
    break; 
 

 
    default: 
 
    alert("Invalid age"); 
 
}

注意,你是不是获取的值18我只是假设它是故意的,但值得指出,并且,您还错过了连接第二条警报的+,因此您的原始示例甚至不会执行。