一,效果圖。 二,代碼。 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>javascript for迴圈</title> </head> <body> <script> cars = ["bmw", "volvo", "saa ...
一,效果圖。
二,代碼。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>javascript for迴圈</title>
</head>
<body>
<script>
cars = ["bmw", "volvo", "saab", "ford"];
for (var i = 0; i < cars.length; i++) {
document.write(cars[i] + "<br>");
}
</script>
<p>點擊按鈕迴圈代碼5次</p>
<button onclick="myFunction()">點擊這裡</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = "";
for (var i = 0; i < 5; i++) {
x = x + "the number is" + i + "<br>";
}
document.getElementById("demo").innerHTML = x;
}
</script>
<p>點擊下麵的按鈕,迴圈遍歷對象"person"的屬性</p>
<button onclick="myFunction()">點擊這裡</button>
<p id="demo1"></p>
<script>
function myFunction() {
var x;
var txt = "";
var person = {
fname: "bill",
lname: "gates",
age: 56
};
for (x in person) {
txt = txt + person[x];
}
document.getElementById("demo1").innerHTML = txt;
}
</script>
</body>
</html>
參考資料:《菜鳥教程》