条件语句 if语句 在编写代码时,经常需要根据不同的条件完成不同的行为。可以在代码中使用 条件语句来完成这个任务。 在 JavaScript中,我们可以使用下面几种条件语句: (1)if语句 在一个指定的条件成立时执行代码。 ■(2)if..else语句 在指定的条件成立时执行代码,当条件不成立时执行另外的代码。 (3)if.. else if.e1se语句 使用这个语句可以选择执行若干块代码中的一个
条件语句 if语句 在编写代码时,经常需要根据不同的条件完成不同的行为。可以在代码中使用 条件语句来完成这个任务。 在 JavaScript 中,我们可以使用下面几种条件语句: (1)if 语句 在一个指定的条件成立时执行代码。 (2)if...else 语句 在指定的条件成立时执行代码,当条件不成立时执行另外的代码。 (3)if...else if....else 语句 使用这个语句可以选择执行若干块代码中的一个
条件语句 if语句 (1)if语句 if语句是最常见的条件语句,基本语法如下所示。条件必须放在if后面的圆 括号中。条件的求值结果永远是一个布尔值,即只能为true或 false。花括号中的 语句不管内容有多少条,只有在给定条件的求值结果为true的情况下才会执行。 f(condition) /执行语句内容 if(1+1=3) alert(It's wrong")
条件语句 if语句 (1)if 语句 if语句是最常见的条件语句,基本语法如下所示。条件必须放在if后面的圆 括号中。条件的求值结果永远是一个布尔值,即只能为true或false。花括号中的 语句不管内容有多少条,只有在给定条件的求值结果为true的情况下才会执行
条件语句 f语句 (1)if语句 实例1: var score=75:∥ Score var msg ∥ Message <html> Head> if (score >=50)t < title>if语句</ title〉 msg="Congratulations! <meta charset="UTF-8> msg + Proceed to the next round. </head> body) var el= Section id="page1"> document. getElementByld(answer) h1>if语句<h1 el text Content= msg <section id="answer>/section> K/section> Script src="demo3-01-1 js"></script> </body> W/htm1>
条件语句 if语句 (1)if 语句 实例1: <html> <head> <title>if语句</title> <meta charset="UTF-8"> </head> <body> <section id="page1"> <h1>if语句</h1> <section id="answer"></section> </section> <script src="demo3-01-1.js"></script> </body> </html> var score = 75; // Score var msg; // Message if (score >= 50) { msg = 'Congratulations!'; msg += ' Proceed to the next round.'; } var el = document.getElementById('answer'); el.textContent = msg;
条件语句 if. else语句 (2)if...else语句 如果希望条件成立时执行一段代码,而条件不成立时执行另一段代码, 那么可以使用if.else语句。 语法: if(条件) 条件表达式 条件成立时执行此代码 语句块1 语句块2 e⊥se 条件不成立时执行此代码
条件语句 if…else语句 (2)if....else语句 如果希望条件成立时执行一段代码,而条件不成立时执行另一段代码, 那么可以使用 if....else 语句。 语法: if (条件) { 条件成立时执行此代码 } else { 条件不成立时执行此代码 }
条件语句 if. else语句 (2) felse语句 实例2 var pass 50: //Pass mark var score=75: / Current score <html> var msg ∥ Message Head> if(score> pass)( < title>if-else语句</ title〉 msg =Congratulations, you <meta charset="UTF-8> passed! </head> else body) msg= Have another go Section id="page1"> h1>if-else语句h1 ir el <section id="answer>/section> document. getElementByld(answer K/section> el textContent= msg: Script src="demo3-02-1 js>/script> </body> W/htm1>
条件语句 if…else语句 (2)if…else 语句 实例2: <html> <head> <title>if-else语句</title> <meta charset="UTF-8"> </head> <body> <section id="page1"> <h1>if-else语句</h1> <section id="answer"></section> </section> <script src="demo3-02-1.js"></script> </body> </html> var pass = 50; // Pass mark var score = 75; // Current score var msg; // Message if (score > pass) { msg = 'Congratulations, you passed!'; } else { msg = 'Have another go!'; } var el = document.getElementById('answer'); el.textContent = msg;