一,效果图。
二,代码。
<!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>
参考资料:《菜鸟教程》