本文通过具体实例解析 JavaScript 中 For In 语句的用法。代码展示了如何遍历自定义对象(如 Student)的属性,以及如何遍历数组元素。通过 alert 输出键值对,帮助开发者理解 For In 在枚举对象属性和数组索引时的基本操作与行为。
For In 语句遍历对象与数组示例
本文通过具体实例介绍 JavaScript 中 For In 语句的使用方法,供读者参考。
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>For In 语句</title>
<script type="text/javascript">
function Student(name, age) {
this.name = name;
this.age = age;
}
var stu = new Student("内马尔", 20);
//遍历对象
for (var s in stu) {
alert(s + ":" + stu[s]);
}
//遍历数组
var myArr = [1, 3, 5, 7, 9];
for (var i in myArr) {
alert(i + ":" + myArr[i]);
}
</script>
</head>
<body>
</body>
</html>
希望本文的内容对您的 JavaScript 编程有所帮助。