解释 JavaScript 中的 “for…in” 语句?
for…in 循环遍历所有对象属性。以下是 JavaScript 中实现 for..in 语句的代码 −
示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.sample,.result {
font-size: 18px;
font-weight: 500;
color: red;
}
</style>
</head>
<body>
<h1>"for...in" statement in JavaScript</h1>
<div class="sample">
{"firstName":"Rohan","lastName":"Sharma","age":22}
</div>
<div class="result" style="color: green;"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to traverse the above object using for..in loop</h3>
<script>
let sampleEle = document.querySelector(".sample");
let resultEle = document.querySelector(".result");
let obj = JSON.parse(sampleEle.innerHTML);
document.querySelector(".Btn").addEventListener("click", () => {
for (let i in obj) {
resultEle.innerHTML += "Property = " + i + " : Value = " + obj[i] + "<br>";
}
});
</script>
</body>
</html>输出
以上代码将生成以下输出 −

点击“单击此处”按钮 −

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP