1 <!DOCTYPE html> 2 <html> 3 <body> 4 <p>点击下面的按钮,循环遍历对象 "person" 的属性。</p> 5 <button onclick="myFunction()">点击这里</button> 6 <p id="demo"></p> 7 8 <script> 9 function myFunction() 10 { 11 var x; 12 var txt=""; 13 var person={"fname":"Bill","lname":"Gates","age":56}; 14 15 for (x in person) 16 { 17 txt = txt + x+‘:‘+ person[x] +‘ ‘; 18 } 19 20 document.getElementById("demo").innerHTML=txt; 21 } 22 </script> 23 </body> 24 </html>
上面代码运行的结果是:fname:Bill lname:Gates age:56
有人不明白17行,txt = 后面为什么还要加txt ,如果去掉的话就只会正剩下最后一个属性。
其实 txt = txt + x+‘:‘+ person[x] +‘ ‘; 的意思就是将值累加起来,我们不妨拆开循环的步骤来看。
第一次循环x=fname person[x]为Bill, txt ="" 则 txt = "" +"fname" +":" +"Bill", txt=“fname:Bill"
第二次循环x= lname person[x]为Gates, txt="fname:Bill" 则 txt = "fname:Bill"+"lname "+":" + "Gates", txt="fname:Bill Iname:Gates"
第三次循环x=age person[x]为56,txt ="fname:Bill Iname:Gates",则txt="fname:Bill Iname:Gates" + "age" + ":" +"56", txt="fname:Bill lname:Gates age:56", 循环结束。
其实 txt = txt + x+‘:‘+ person[x] +‘ ‘; 可以直接写成 txt += x+‘:‘+ person[x] +‘ ‘;