zoukankan      html  css  js  c++  java
  • JS之For---in 语句

    下面说一下for… in语句。可直接把下面的代码复制到浏览器的控制台或Node环境下去执行。

    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    //用来快速迭代对象。

    var o ={name:'dylan',age:24,num:110};
    for(var test in o){
      console.log("o["+test+"]= "+o[test]);
    }
    console.log("~~~~~~~~~~~")
    Object.prototype.getName =function(){return this.name};
    o.getAge=function(){returnthis.age};
    
    for(var test in o){   console.log("o["+test+"]= "+o[test]); } console.log(o.getName()+o.getAge());

    //getName并不是o的方法,它是Object原型方法,而Object原型方法会被

    //所有Object类型实例对象所继承的.

    //因此可以看出使用for...in语句不仅能迭代出对象的属性,还可迭代出其原型方法。

    console.log("~~~~hasOwnPyroperty~~~~~~~");
    for(var test in o){
      if(o.hasOwnProperty(test)){
           console.log("o["+test+"]= "+o[test]);
      }
    }

    //通过调用hasOwnProperty方法过滤原型中的方法。

    //如果o有二个undefined和null属性呢?.

    o.undefined ='undefined';
    o.null = 'null';
    console.log(o);
    console.log(o.toString());
    console.log(o.valueOf());
    for(var test in o){   if(o.hasOwnProperty(test)){   console.log("o["+test+"]= "+o[test]);   } }

    //如果 o=null;

    o=undefined; //o=null;  
    for(var test in o){
      if(o.hasOwnProperty(test)){
           console.log("o["+test+"]= "+o[test]);
      }
    }

    //既不会报错,也不会输出。但如果是在低版本浏览器,很有可能报异常。因此在使用

    //for-in之前,可以先过滤一下迭代对象是否为null或undefined.

    console.log("~~~~Iteratearray~~~~~~~");

    //迭代数组可以吗?

    var a = [26,'hellworld',newDate()];
    for(var pro in a){
      console.log("a["+pro+"]="+a[pro]);
    }

    //Array也是一种对象,因此原型的getName方法同样被迭代出来。

    function keys(obj){
    var aRaa = [];
    var i=0;
    for(aRaa[i++] in obj);
      return aRaa;
    }
    console.log(keys(o));
    a.index = a.length;
    console.log(a);
    console.log(keys(a));

    //当你以为是对象数组时,执行下面一条语句,发现又会发错。

    //console.log(a[index]); //报错,index未定义

    //但是下面这条语句不会报错。

    console.log(a.index);
    console.log(a[getName]);

    //当迭代数组时,尽量少用for....in 语句,这样可以减少不必要的错误。用下面的常用方法,更好!

    for(var i=0,lenght =a.length;i<lenght;i++){
      console.log(a[i]);
    };

    Dylan童鞋】

    关注Dylan童鞋,请搜索微信号:DylanTongXue 

    推送时间为:周一,周三,周四,周日晚上920分左右。

    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    查看历史记录请回复1~9之间的数字。比如查看第六篇文章直接回复数字:。显示本帮助菜单,回复"H"

     

  • 相关阅读:
    cf D. Vessels
    cf C. Hamburgers
    zoj 3758 Singles' Day
    zoj 3777 Problem Arrangement
    zoj 3778 Talented Chef
    hdu 5087 Revenge of LIS II
    zoj 3785 What day is that day?
    zoj 3787 Access System
    判断给定图是否存在合法拓扑排序
    树-堆结构练习——合并果子之哈夫曼树
  • 原文地址:https://www.cnblogs.com/idayln/p/3341472.html
Copyright © 2011-2022 走看看