浅谈javascript中的For in语法

相信大家都使用过javascript中的for循环,主要用来遍历数组对象,方便执行重复操作,体现代码的重用性。但是,应为数组的索引一般是整 型的数字,当遇到JSON对象或者object对象时,就不能使用for循环遍历了,应当使用for in函数遍历对象,这里就谈谈个人对for in的理解。

      首先,虽然叫For in语法但关键字还是用for,这个语法还可以用来遍历对象,拿到的是对象的属性名称,然后通过对象名[属性名称]就可以拿到对象。个人觉得,理解这个语法的本质,关键在于理解每次循环得到的到底是什么。

  for in功能的实现得益于javascript的数组索引可以是字符串,是从for循环扩展开来的。下面举个例子,

 

<html>
<head>
    <title></title>
    <meta content="text/html" charset="utf-8"/>
    <style>
        input[type="button"]{
            width: 100px;
            height: 40px;
            background-color: #f5deb3;
            border-radius: 11px;
            outline: 0px;
            color: #ff2692;
            font-size: 16px;
            font-weight: bold;
        }
        #content{
            width: 400px;
            height: 400px;
            margin-top: 10px;
            color: #4169e1;
            font-size: 20px;
            font-weight: bold;
        }
    </style>
</head>
<body>
<input type="button" id="c1" name="c1" οnclick="f1();" value="click one"/>    
<input type="button" id="c2" name="c2" οnclick="f2();" value="click two"/>    
<div id="content"></div>
</body>
<script type="text/javascript">
    var mycolors = new Array('blue','red','yellow');
    function f1(){
        var content="";
        for(var key in mycolors){
            content += key+": "+mycolors[key]+"<br/>";
        }
        document.getElementById("content").innerHTML = content;
    }
    function User(){
        this.name;
        this.age;
    }
    function f2(){
        var u1=new User();
        u1.uname="张三";
        u1.age="18";

        var content="";
        for(var key in u1){
            content += key+": "+u1[key]+"<br/>";
        }
        document.getElementById("content").innerHTML = content;
    }
</script>
</html>

点击按钮one后:

    0: blue  

    1: red

    2: yellow。
点击按钮two后:
    uname: 张三
    age: 18
这就是上面代码输出的结果,还可以试想,如果u1中有一个方法
 u1.say=function(){
           alert("hello");
  },那么点击two后,就应该输出
  uname: 张三
  age: 18
  say: function(){ alert("hello"); }
  所以,使用for in可以遍历json对象和obj对象!纯属个人心得,不对的地方,请多多指教!

 

转载于:https://www.cnblogs.com/yl1989/p/3948130.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值