博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
优雅编写js条件语句_如何在Go中编写条件语句
阅读量:2508 次
发布时间:2019-05-11

本文共 17126 字,大约阅读时间需要 57 分钟。

优雅编写js条件语句

介绍 (Introduction)

Conditional statements are part of every programming language. With conditional statements, we can have code that sometimes runs and at other times does not run, depending on the conditions of the program at that time.

条件语句是每种编程语言的一部分。 使用条件语句,根据当时程序的条件,我们可以使某些代码有时运行而在其他时间不运行。

When we fully execute each statement of a program, we are not asking the program to evaluate specific conditions. By using conditional statements, programs can determine whether certain conditions are being met and then be told what to do next.

当我们完全执行程序的每个语句时,我们并没有要求程序评估特定条件。 通过使用条件语句,程序可以确定是否满足某些条件,然后告知下一步该怎么做。

Let’s look at some examples where we would use conditional statements:

让我们看一些使用条件语句的示例:

  • If the student receives over 65% on her test, report that her grade passes; if not, report that her grade fails.

    如果学生的考试成绩超过65%,则报告其成绩通过; 如果不是,请报告她的成绩不及格。
  • If he has money in his account, calculate interest; if he doesn’t, charge a penalty fee.

    如果他的帐户中有钱,请计算利息; 如果他不这样做,则收取罚款。
  • If they buy 10 oranges or more, calculate a discount of 5%; if they buy fewer, then don’t.

    如果他们购买10个或更多的橙子,请计算5%的折扣; 如果他们少买,那就不要。

Through evaluating conditions and assigning code to run based on whether or not those conditions are met, we are writing conditional code.

通过评估条件并根据是否满足这些条件来分配要运行的代码,我们正在编写条件代码。

This tutorial will take you through writing conditional statements in the Go programming language.

本教程将带您完成用Go编程语言编写条件语句的过程。

如果陈述 (If Statements)

We will start with the if statement, which will evaluate whether a statement is true or false, and run code only in the case that the statement is true.

我们将从if语句开始,该语句将评估一个语句是true还是false,并且仅在该语句为true的情况下运行代码。

In a plain text editor, open a file and write the following code:

在纯文本编辑器中,打开一个文件并编写以下代码:

grade.go
grade.go
package mainimport "fmt"func main() {    grade := 70    if grade >= 65 {        fmt.Println("Passing grade")    }}

With this code, we have the variable grade and are giving it the integer value of 70. We are then using the if statement to evaluate whether or not the variable grade is greater than or equal ( >= ) to 65. If it does meet this condition, we are telling the program to print out the Passing grade.

使用此代码,我们得到了变量grade ,并为其赋予了整数值70 。 然后,我们使用if语句来评估变量等级是否大于或等于( >= )等于65 。 如果确实满足此条件,我们将告诉程序打印出 Passing grade

Save the program as grade.go and run it in a with the command go run grade.go.

将程序另存为grade.go ,并在使用命令go run grade.go go run grade.go

In this case, the grade of 70 does meet the condition of being greater than or equal to 65, so you will receive the following output once you run the program:

在这种情况下,等级70 确实满足大于或等于65的条件,因此一旦运行该程序,您将收到以下输出:

Output   
Passing grade

Let’s now change the result of this program by changing the value of the grade variable to 60:

现在,通过将grade变量的值更改为60来更改该程序的结果:

grade.go
grade.go
package mainimport "fmt"func main() {    grade := 60    if grade >= 65 {        fmt.Println("Passing grade")    }}

When we save and run this code, we will receive no output because the condition was not met and we did not tell the program to execute another statement.

当我们保存并运行代码,我们将在收到无输出,因为条件成立,我们没有告诉程序执行另一个说法。

To give one more example, let us calculate whether a bank account balance is below 0. Let’s create a file called account.go and write the following program:

再举一个例子,让我们计算一下银行账户余额是否低于0。让我们创建一个名为account.go的文件并编写以下程序:

account.go
account.go
package mainimport "fmt"func main() {    balance := -5    if balance < 0 {        fmt.Println("Balance is below 0, add funds now or you will be charged a penalty.")    }}

When we run the program with go run account.go, we’ll receive the following output:

当我们使用go run account.go运行程序时,将收到以下输出:

Output   
Balance is below 0, add funds now or you will be charged a penalty.

In the program we initialized the variable balance with the value of -5, which is less than 0. Since the balance met the condition of the if statement (balance < 0), once we save and run the code, we will receive the string output. Again, if we change the balance to 0 or a positive number, we will receive no output.

在程序中,我们将变量balance初始化为小于-5的值-5 。由于balance满足了if语句的条件( balance < 0 ),因此一旦保存并运行代码,我们将收到字符串输出。 同样,如果将余额更改为0或正数,则不会收到任何输出。

其他声明 (Else Statements)

It is likely that we will want the program to do something even when an if statement evaluates to false. In our grade example, we will want output whether the grade is passing or failing.

即使if语句的值为false,我们也可能希望程序执行某些操作。 在我们的成绩示例中,无论成绩是及格还是不及格,我们都将需要输出。

To do this, we will add an else statement to the grade condition above that is constructed like this:

为此,我们将在上面的成绩条件中添加一个else语句,其构造如下:

grade.go
grade.go
package mainimport "fmt"func main() {    grade := 60    if grade >= 65 {        fmt.Println("Passing grade")    } else {        fmt.Println("Failing grade")    }}

Since the grade variable has the value of 60, the if statement evaluates as false, so the program will not print out Passing grade. The else statement that follows tells the program to do something anyway.

由于等级变量的值为60 ,因此if语句的评估结果为false,因此程序不会打印出Passing gradeelse语句告诉程序无论如何都要做一些事情。

When we save and run the program, we’ll receive the following output:

保存并运行程序后,将收到以下输出:

Output   
Failing grade

If we then rewrite the program to give the grade a value of 65 or higher, we will instead receive the output Passing grade.

如果我们随后重写程序以使该等级的分数65或大于65 ,则将收到输出Passing grade

To add an else statement to the bank account example, we rewrite the code like this:

要将else语句添加到银行帐户示例中,我们将代码重写为:

account.go
account.go
package mainimport "fmt"func main() {    balance := 522    if balance < 0 {        fmt.Println("Balance is below 0, add funds now or you will be charged a penalty.")    } else {        fmt.Println("Your balance is 0 or above.")    }}
Output   
Your balance is 0 or above.

Here, we changed the balance variable value to a positive number so that the else statement will print. To get the first if statement to print, we can rewrite the value to a negative number.

在这里,我们将balance变量值更改为正数,以便打印else语句。 要获得要打印的第一个if语句,我们可以将值重写为负数。

By combining an if statement with an else statement, you are constructing a two-part conditional statement that will tell the computer to execute certain code whether or not the if condition is met.

通过将if语句与else语句组合,您将构造一个分为两部分的条件语句,该条件语句将告诉计算机执行某些代码是否满足if条件。

其他语句 (Else if Statements)

So far, we have presented a option for conditional statements, with each if statement evaluating to either true or false. In many cases, we will want a program that evaluates more than two possible outcomes. For this, we will use an else if statement, which is written in Go as else if. The else if or else if statement looks like the if statement and will evaluate another condition.

到目前为止,我们为条件语句提供了一个选项,每个if语句的评估结果为true或false。 在许多情况下,我们需要一个程序来评估两个以上可能的结果。 为此,我们将使用else if语句,该语句与go else if编写。 else if or else if语句类似于if语句,并将评估另一个条件。

In the bank account program, we may want to have three discrete outputs for three different situations:

在银行帐户程序中,我们可能希望针对三种不同情况具有三个离散输出:

  • The balance is below 0

    余额低于0
  • The balance is equal to 0

    余额等于0
  • The balance is above 0

    余额高于0

The else if statement will be placed between the if statement and the else statement as follows:

else if语句将放置在if语句和else语句之间,如下所示:

account.go
account.go
package mainimport "fmt"func main() {    balance := 522    if balance < 0 {        fmt.Println("Balance is below 0, add funds now or you will be charged a penalty.")    } else if balance == 0 {        fmt.Println("Balance is equal to 0, add funds soon.")    } else {        fmt.Println("Your balance is 0 or above.")    }}

Now, there are three possible outputs that can occur once we run the program:

现在,一旦运行程序,可能会发生三种可能的输出:

  • If the variable balance is equal to 0 we will receive the output from the else if statement (Balance is equal to 0, add funds soon.)

    如果变量balance等于0我们将从else if语句接收输出( Balance is equal to 0, add funds soon. )

  • If the variable balance is set to a positive number, we will receive the output from the else statement (Your balance is 0 or above.).

    如果将变量balance设置为正数,我们将收到else语句的输出( Your balance is 0 or above. )。

  • If the variable balance is set to a negative number, the output will be the string from the if statement (Balance is below 0, add funds now or you will be charged a penalty).

    如果变量balance设置为负数,则输出将为if语句的字符串( Balance is below 0, add funds now or you will be charged a penalty )。

What if we want to have more than three possibilities, though? We can do this by writing more than one else if statement into our code.

但是,如果我们想拥有三种以上的可能性怎么办? 我们可以通过在代码中编写多个else if语句来做到这一点。

In the grade.go program, let’s rewrite the code so that there are a few letter grades corresponding to ranges of numerical grades:

grade.go程序中,让我们重写代码,以便有几个字母等级对应于数字等级的范围:

  • 90 or above is equivalent to an A grade

    90或以上相当于A级
  • 80-89 is equivalent to a B grade

    80-89相当于B级
  • 70-79 is equivalent to a C grade

    70-79相当于C级
  • 65-69 is equivalent to a D grade

    65-69相当于D级
  • 64 or below is equivalent to an F grade

    64或以下相当于F级

To run this code, we will need one if statement, three else if statements, and an else statement that will handle all failing cases.

要运行此代码,我们将需要一个if语句,三个else if语句以及一个处理所有失败案例的else语句。

Let’s rewrite the code from the preceding example to have strings that print out each of the letter grades. We can keep our else statement the same.

让我们重写前面示例中的代码,以使字符串打印出每个字母等级。 我们可以保持else语句不变。

grade.go
grade.go
package mainimport "fmt"func main() {    grade := 60    if grade >= 90 {        fmt.Println("A grade")    } else if grade >= 80 {        fmt.Println("B grade")    } else if grade >= 70 {        fmt.Println("C grade")    } else if grade >= 65 {        fmt.Println("D grade")    } else {        fmt.Println("Failing grade")    }}

Since else if statements will evaluate in order, we can keep our statements pretty basic. This program is completing the following steps:

else if语句将按顺序求值,则我们可以使语句保持基本状态。 该程序正在完成以下步骤:

  1. If the grade is greater than 90, the program will print A grade, if the grade is less than 90, the program will continue to the next statement…

    如果成绩大于90,则程序将打印A grade ;如果成绩小于90,则程序将继续执行下一个语句…

  2. If the grade is greater than or equal to 80, the program will print B grade, if the grade is 79 or less, the program will continue to the next statement…

    如果成绩大于或等于80,程序将打印B grade ,如果成绩为79或更低,程序将继续执行下一个语句…

  3. If the grade is greater than or equal to 70, the program will print C grade, if the grade is 69 or less, the program will continue to the next statement…

    如果成绩大于或等于70,则程序将打印C grade ;如果成绩为69或以下,则程序将继续执行下一个语句…

  4. If the grade is greater than or equal to 65, the program will print D grade, if the grade is 64 or less, the program will continue to the next statement…

    如果成绩大于或等于65,程序将打印D grade ,如果成绩为64或小于64,程序将继续执行下一个语句…

  5. The program will print Failing grade because all of the above conditions were not met.

    由于不满足所有上述条件,程序将打印Failing grade

嵌套If语句 (Nested If Statements)

Once you are feeling comfortable with the if, else if, and else statements, you can move on to nested conditional statements. We can use nested if statements for situations where we want to check for a secondary condition if the first condition executes as true. For this, we can have an if-else statement inside of another if-else statement. Let’s look at the syntax of a nested if statement:

一旦对ifelse ifelse语句感到满意,就可以继续使用嵌套的条件语句。 如果第一个条件执行为true,则可以在需要检查第二个条件的情况下使用嵌套的if语句。 为此,我们可以在另一个if-else语句中包含一个if-else语句。 让我们看一下嵌套的if语句的语法:

if statement1 { // outer if statement    fmt.Println("true")    if nested_statement { // nested if statement        fmt.Println("yes")    } else { // nested else statement        fmt.Println("no")    }} else { // outer else statement    fmt.Println("false")}

A few possible outputs can result from this code:

此代码可能会产生一些输出:

  • If statement1 evaluates to true, the program will then evaluate whether the nested_statement also evaluates to true. If both cases are true, the output will be:

    如果statement1评估为true,则程序将评估nested_statement是否也评估为true。 如果两种情况都成立,则输出将是:

Output    
trueyes
Output    
trueyes
  • If, however, statement1 evaluates to true, but nested_statement evaluates to false, then the output will be:

    但是,如果statement1计算结果为true,而nested_statement计算结果为false,则输出为:

Output    
trueno
  • And if statement1 evaluates to false, the nested if-else statement will not run, so the else statement will run alone, and the output will be:

    并且如果statement1计算结果为false,则嵌套的if-else语句将不会运行,因此else语句将单独运行,并且输出将为:

Output    
false
Output    
false

We can also have multiple if statements nested throughout our code:

我们还可以在整个代码中嵌套多个if语句:

if statement1 { // outer if    fmt.Println("hello world")    if nested_statement1 { // first nested if        fmt.Println("yes")    } else if nested_statement2 { // first nested else if        fmt.Println("maybe")    } else { // first nested else        fmt.Println("no")    }} else if statement2 { // outer else if    fmt.Println("hello galaxy")    if nested_statement3 { // second nested if        fmt.Println("yes")    } else if nested_statement4 { // second nested else if        fmt.Println("maybe")    } else { // second nested else        fmt.Println("no")    }} else { // outer else    statement("hello universe")}

In this code, there is a nested if statement inside each if statement in addition to the else if statement. This will allow for more options within each condition.

在这段代码中,有一个嵌套if语句中的每个里面if语句除了else if语句。 这将在每个条件下提供更多选项。

Let’s look at an example of nested if statements with our grade.go program. We can check for whether a grade is passing first (greater than or equal to 65%), then evaluate which letter grade the numerical grade should be equivalent to. If the grade is not passing, though, we do not need to run through the letter grades, and instead can have the program report that the grade is failing. Our modified code with the nested if statement will look like this:

让我们看一下我们grade.go程序中嵌套if语句的示例。 我们可以检查一个等级是否首先通过(大于或等于65%),然后评估该数字等级应该等于哪个字母等级。 但是,如果成绩不及格,我们就不需要复习字母成绩,而可以让程序报告成绩不及格。 带有嵌套if语句的修改后的代码将如下所示:

grade.go
grade.go
package mainimport "fmt"func main() {    grade := 92    if grade >= 65 {        fmt.Print("Passing grade of: ")        if grade >= 90 {            fmt.Println("A")        } else if grade >= 80 {            fmt.Println("B")        } else if grade >= 70 {            fmt.Println("C")        } else if grade >= 65 {            fmt.Println("D")        }    } else {        fmt.Println("Failing grade")    }}

If we run the code with the variable grade set to the integer value 92, the first condition is met, and the program will print out Passing grade of:. Next, it will check to see if the grade is greater than or equal to 90, and since this condition is also met, it will print out A.

如果我们将变量grade设置为整数值92来运行代码,则满足第一个条件,程序将打印出Passing grade of: 。 接下来,它将检查等级是否大于或等于90,并且由于也满足此条件,因此它将打印出A

If we run the code with the grade variable set to 60, then the first condition is not met, so the program will skip the nested if statements and move down to the else statement, with the program printing out Failing grade.

如果我们将grade变量设置为60运行代码,则不满足第一个条件,因此程序将跳过嵌套的if语句,然后移至else语句,并打印出Failing grade

We can of course add even more options to this, and use a second layer of nested if statements. Perhaps we will want to evaluate for grades of A+, A and A- separately. We can do so by first checking if the grade is passing, then checking to see if the grade is 90 or above, then checking to see if the grade is over 96 for an A+:

我们当然可以为此添加更多选项,并使用第二层嵌套的if语句。 也许我们将要分别评估A +,A和A-的等级。 我们可以这样进行:首先检查成绩是否及格,然后检查成绩是否达到90或以上,然后检查A +的成绩是否超过96:

grade.go
grade.go
...if grade >= 65 {    fmt.Print("Passing grade of: ")    if grade >= 90 {        if grade > 96 {            fmt.Println("A+")        } else if grade > 93 && grade <= 96 {            fmt.Println("A")        } else {            fmt.Println("A-")        }...

In this code, for a grade variable set to 96, the program will run the following:

在此代码中,对于设置为96grade变量,程序将运行以下代码:

  1. Check if the grade is greater than or equal to 65 (true)

    检查成绩是否大于或等于65(是)
  2. Print out Passing grade of:

    打印输出Passing grade of:

  3. Check if the grade is greater than or equal to 90 (true)

    检查成绩是否大于或等于90(是)
  4. Check if the grade is greater than 96 (false)

    检查成绩是否大于96(假)
  5. Check if the grade is greater than 93 and also less than or equal to 96 (true)

    检查等级是否大于93并且小于或等于96(是)
  6. Print A

    打印A

  7. Leave these nested conditional statements and continue with remaining code

    保留这些嵌套的条件语句,然后继续其余代码

The output of the program for a grade of 96 therefore looks like this:

因此,该程序的等级为96的输出如下所示:

Output   
Passing grade of: A

Nested if statements can provide the opportunity to add several specific levels of conditions to your code.

嵌套的if语句可以为在代码中添加几个特定级别的条件提供机会。

结论 (Conclusion)

By using conditional statements like the if statement, you will have greater control over what your program executes. Conditional statements tell the program to evaluate whether a certain condition is being met. If the condition is met it will execute specific code, but if it is not met the program will continue to move down to other code.

通过使用条件语句(如if语句),您可以更好地控制程序执行的内容。 条件语句告诉程序评估是否满足特定条件。 如果满足条件,它将执行特定的代码,但是如果不满足,程序将继续向下移动到其他代码。

To continue practicing conditional statements, try using different to gain more familiarity with conditional statements.

要继续练习条件语句,请尝试使用不同的来更熟悉条件语句。

翻译自:

优雅编写js条件语句

转载地址:http://tohgb.baihongyu.com/

你可能感兴趣的文章
有道单词导入 大量有道单词 生词本 批量导入 添加 有道单词XML 背单词
查看>>
jQuery Easing动画效果扩展插件
查看>>
bzoj 1002 [FJOI2007]轮状病毒 Matrix-Tree定理+递推
查看>>
Selenium WebDriver- 操作JavaScript的Alert弹窗
查看>>
娘的,自己的求逆序对模板又不好使了。。。。。。。。
查看>>
C#面向对象模式设计第十四讲:Template Method 模板模式(行为型模式)
查看>>
linux后台运行命令:&和nohup
查看>>
springboot + shiro学习(配置SecurityManager,Realm)
查看>>
http://desk.zol.com.cn/1600x900/
查看>>
Linux基础之命令练习Day3-文件管理:cat,tar,gzip,vim,ln
查看>>
iOS中使用nil NULL NSNULL的区别
查看>>
Hdu1754-线段树-单点更新
查看>>
在python中使用正则表达式(一)
查看>>
asp.net mvc 4.0的部署
查看>>
WordPress资源站点推荐
查看>>
Python性能鸡汤
查看>>
android Manifest.xml选项
查看>>
Cookie/Session机制具体解释
查看>>
ATMEGA16 IOport相关汇总
查看>>
有意思的cmd命令
查看>>