循環遍歷對象的屬性


 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] +'  ';

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM