![[译]Javascript中的Ternary operator [译]Javascript中的Ternary operator](https://image.shishitao.com:8440/aHR0cHM6Ly9ia3FzaW1nLmlrYWZhbi5jb20vdXBsb2FkL2NoYXRncHQtcy5wbmc%2FIQ%3D%3D.png?!?w=700&webp=1)
本文翻译youtube上的up主kudvenkat的javascript tutorial播放单
源地址在此:
https://www.youtube.com/watch?v=PMsVM7rjupU&list=PL6n9fhu94yhUA99nOsJkKXBqokT3MBK0b
Ternary operator可以作为if..else..语句的一种简写
以下是ternary operator的格式
Boolean语句开头,接着一个?符号,如果Boolean语句为true,则?号后第一个语句运行,如果Boolean语句为false,则:符号后面的那个语句则运行
以下例子会检查一个数字是为奇数或者偶数.我们用的是if-else语句
var userInput = Number(prompt("Please enter a number"));
var message = "";
if (userInput % 2 == 0)
{
message = "Your number is even";
}
else
{
message = "Your number is odd";
}
alert(message);
Ternary operator例子:在以上的例子中if-else语句被ternary operator如下替换
var userInput = Number(prompt("Please enter a number"));
var message = userInput % 2 == 0 ? "Your number is even" : "Your number is odd";
alert(message);
多个if-else-if语句可以被ternary operator替换
以下的例子会根据月份的数字来显示月份的名字,该例子由if-else-if语句所写
var userInput = Number(prompt("Please enter a month number - 1, 2 or 3"));
var monthName = ""; if (userInput == 1) {
monthName = "January";
}
else if (userInput == 2) {
monthName = "February";
}
else if (userInput == 3) {
monthName = "March";
}
else {
monthName = "Unknown month number"
} alert(monthName);
ternary operator基于多个条件的例子:在以下的例子中,if-else-if语句会被ternary operator所取代
var userInput = Number(prompt("Please enter a month number - 1, 2 or 3"));
var monthName = userInput == 1 ? "January" : userInput == 2 ? "February" : userInput == 3 ? "March" : "Unknown month number";
alert(monthName);