JavaScript中通过for…in语句遍历对象,JS中我们可以通过for..in语句输出对象的每一个元素和元素值
<!DOCTYPE html> <html> <body> <p>75271.com Click the button to loop through the properties of an object named "person".</p> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script> function myFunction() { var x; var txt=""; var person={fname:"John",lname:"Doe",age:25}; for (x in person) { txt=txt + person[x]; } document.getElementById("demo").innerHTML=txt; } </script> </body> </html>
上面的代码输出
JohnDoe25