1、流程控制語句
1.1 代碼
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>标題</title>
<style type="text/css"> </style>
<script type="text/javascript">
/*
流程控制語句:
JS中的程式是從上到下一行一行執行的
文法1:
if(條件表達式){
語句
}
成功執行括号的内容,一條語句可以省略括号
文法2:
if(條件表達式){
語句
}else{
語句
}
文法3:
if(條件表達式){
語句
}else if(條件表達式){
語句
}else if(條件表達式){
語句
}else{
語句
}
*/
var a = 1, b = 2;
if(a < b){
console.log("成立");
}
if(a > b){
console.log("1111");
}else{
console.log("22222");
}
</script>
</head>
<body>
</body>
</html>
1.2 測試結果
2、彈窗提示輸入内容
2.1 代碼
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>彈窗</title>
<style type="text/css"> </style>
<script type="text/javascript">
/*
prompt 可以彈出一個提示框,該提示框中會帶有一個文本框
使用者可以在文本框中輸入一段内容,該函數需要一個字元串作為參數,
該字元串作為彈窗的提示内容。
使用者輸入的内容将會作為函數的傳回值 傳回,可以定義一個變量接收該内容
*/
var age = prompt("請輸入你的年齡:")
console.log(age);
</script>
</head>
<body>
</body>
</html>
2.2 測試結果
3、條件分支語句
3.1 代碼
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>條件分支語句</title>
<style type="text/css"> </style>
<script type="text/javascript">
/*
條件分支語句也叫switch語句
文法
switch(條件表達式){
case : 表達式:
語句...
break;
case : 表達式:
語句...
break;
case : 表達式:
語句...
break;
default:
語句...
break;
}
*/
var num = prompt("請輸入整數數字")
//從彈窗輸入的是字元串,需要強制類型轉換為num,switch中的判斷是 === 比較類型和内容
num = Number(num)
switch(num){
case 1:
console.log("1");
break;
case 2:
console.log("2");
break;
default:
console.log("預設值");
break;
}
</script>
</head>
<body>
</body>
</html>
3.2 測試結果
4、while和 do...while循環
4.1 代碼
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>while循環語句</title>
<style type="text/css"> </style>
<script type="text/javascript">
/*
循環語句:
通過循環語句可以反複的執行一段代碼多次
文法:
while(表達式){
語句...
}
執行流程: 表達式成立,執行語句
do...while() 循環
文法:
do{
語句
}while(表達式)
執行流程: 先執行一遍循環體,然後條件判斷
*/
var n = 1 ;
//條件表達式寫死為true的循環,死循環。可以使用break終止循環
/*
while(true){
alert(n++);
break;
}
*/
while(n < 6){
document.write(n++ +"<br>")
}
</script>
</head>
<body>
</body>
</html>
4.2 測試結果
5、for循環
5.1 代碼
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>for循環</title>
<style type="text/css"> </style>
<script type="text/javascript">
/*
for語句,也是一個循環語句,也稱為for循環
文法 :
for(初始化表達式;條件表達式; 更新表達式){
語句...
}
*/
for(var i =0 ; i < 10; i++){
document.write(i+"<br>")
}
</script>
</head>
<body>
</body>
</html>