基本格式已省略,直接列出代码部分
1.for语句示例
<body>
<!-- for,点击,循环5次 -->
<button type="button" onclick="myFun1()">click</button>
<p id="demo1"></p>
<script>
function myFun1() {
var x="";
for (var i = 0; i < 5; i++) {
x = x+"the number is "+i+"<br>";
}
document.getElementById("demo1").innerHTML=x;
}
</script>
<!-- for/in循环遍历 -->
<button type="button" onclick="myFun2()">click</button>
<p id="demo2"></p>
<script>
function myFun2() {
var txt="";
var person = {fname:"L",lname:"p ",age:18};
for (var x in person) {
txt = txt+person[x];
}
document.getElementById("demo2").innerHTML=txt;
}
</script>
</body>
2.if语句示例
<body>
<!-- 使用if判断时间,并执行语句 -->
<p>如果时间早于20:00,会出现good day,否则将为good evening</p>
<button type="button" onclick="myFun()">click</button>
<p id="demo"></p>
<script>
function myFun() {
var x = "";
var time = new Date().getHours();
if (time<20) {
x = "good day";
} else {
x = "good evening"
}
document.getElementById("demo").innerHTML=x;
}
</script>
<!-- 使用多层if-else语句 -->
<script>
//例子
if (time < 10) {
x="good morning";
} else if {
x="good day";
} else {
x="good evening";
}
</script>
</body>
3.while语句示例
<body>
<!-- while循环 -->
<button type="button" onclick="myFun1()">click</button>
<p id="demo1"></p>
<script>
function myFun1() {
var x="",i=0;
while (i<5) {
x=x+"the number is "+i+"<br>";
i++;
}
document.getElementById("demo1").innerHTML=x;
}
</script>
<!-- do-while循环 -->
<button type="button" onclick="myFun2()">click</button>
<p id="demo2"></p>
<script>
function myFun2() {
var x="",i=0;
do { //即使是false也会执行一次
x=x+"the number is "+i+"<br>";
i++;
} while (i<5)
document.getElementById("demo2").innerHTML=x;
}
</script>
</body>
4.switch语句示例
<body>
<script>
var day = new Date().getDay();
switch (day) {
case 0: //Sunday为0
x="today it's Sunday";
break;
case 1:
x="today it's Monday";
break;
case 2:
x="today it's Tuesday";
break;
case 3:
x="today it's Wednesday";
break;
case 4:
x="today it's Thursday";
break;
case 5:
x="today it's Friday";
break;
case 6:
x="today it's Saturday";
break;
default:
x="error";
}
document.write(x);
</script>
</body>
5.break与continue
<body>
<!-- 和一般的break、continue基本概念一样 -->
<!--
对 JavaScript 语句进行标记。
如需标记 JavaScript 语句,请在语句之前加上冒号:
语句
test:
break 和 continue 语句仅仅是能够跳出代码块的语句。
语法
break testname;
continue testname;
continue 语句(带有或不带标签引用)只能用在循环中.
break 语句(不带标签引用),只能用在循环或 switch 中.
通过标签引用,break 语句可用于跳出任何 JavaScript 代码块.
-->
<script>
//例子
cars=["a","b","c","d"];
list:
{
document.write(cars[0] + "<br>");
document.write(cars[1] + "<br>");
document.write(cars[2] + "<br>");
break list;
document.write(cars[3] + "<br>");
document.write(cars[4] + "<br>");
document.write(cars[5] + "<br>");
}
</script>
</body>