This article is currently in the process of being translated into Chinese (~1% done).
The IF statement
控制你代码的流程是在编程中最重要的概念之一,而最基本的控制结构大概就是if语句。它简单地能让你指定一个条件来表明后续几行代码是否应该执行。这里给了一个简单的示例:
if(something == true)
alert("something is true!");
第一行是if语句——一个简单的条件用于表明下一行代码是否应该执行。我们可以试下把它改成某些从用户输入来的内容,来测试它是否正常工作:
var answer = confirm("Is it true?");
if(answer == true)
alert("I knew it was true!");
记住,正如在这个教程中我们在前面所讨论的一样:如果你需要让一个条件包含多行语句,你需要用花括号把它们括起来,创建一个代码块:
var answer = confirm("Is it true?");
if(answer == true)
{
alert("I knew it was true!");
alert("I knew it too!");
}
多条件
The if statement works simply by checking whether the supplied condition can be considered true. This allows you to specify as many conditions as you want to. We can use the && (AND) as well as the || (OR) operators (more on those later) to add conditions:
var age = prompt("What's your age?");
var hasDriversLicense = confirm("Do you have a drivers license?")
if(hasDriversLicense || (age >= 18 && age <= 80))
alert("I guess you can be allowed to drive a car!");
So, if you have a drivers license, OR an appropriate age (between 18 and 80), this code will allow you to drive a car. That's not a very realistic example, but hopefully it does the job of illustrating how you can use multiple conditions in your if statement.
if...else
Our current if statement only does something if the condition is true, but we may need to do something else in case its NOT true. For that, we have the else statement, which obviously only works together with the if statement. Here's an example:
var answer = confirm("Is it true?");
if(answer == true)
alert("I knew it was true!");
else
alert("Oh well, guess not then...");
And again, if you need more lines of code for one (or both) of the conditions, just surround it with a block:
var answer = confirm("Is it true?");
if(answer == true)
{
alert("I knew it was true!");
// More true code...
}
else
{
alert("Oh well, guess not then...");
// More false code...
}
if...else...if
Using nested if statements, we can create some pretty advanced logic:
var age = prompt("What's your age?");
if(age < 1)
alert("Infant");
else if(age < 13)
alert("Child");
else if(age < 18)
alert("Teenager");
else
alert("Adult");
If you want or need to, you can of course use blocks around the conditions, just like we saw in previous examples.
Summary
The if statement is easy to use and understand, yet so powerful. If you're new to the world of programming, you might be surprised when you realize just how common they are. You should also know that there's an alternative, shorter notation for doing if...else statements, but we'll discuss that in the chapter on operators. For now, let's move on to some of the more advanced control structures.