zoukankan      html  css  js  c++  java
  • 循环遍历对象的属性

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

  • 相关阅读:
    Java程序员必会的工具库,代码量减少90%
    Git常用操作
    Eclipse开发环境配置
    Spring Cloud Alibaba Nacos 在Windows10下启动
    MySQL连接异常Communications link failure
    Spring Cloud Alibaba Nacos2.0踩坑
    Spring Cloud Alibaba Nacos配置中心与服务发现
    RocketMQ学习笔记
    Linux开发环境配置
    Clumper尝鲜
  • 原文地址:https://www.cnblogs.com/sanerandm/p/8350684.html
Copyright © 2011-2022 走看看