javascript中in,of

总结:遍历数组使用of,遍历{a:”aaa”,b:”bbb”}对象使用in

in表示指定对象中含有指定属性名

var arr = ['a','b','c','d'];
1 in arr //true
'length' in arr //true

var obj = {a:'aaa', b:'ddd', c:undefined};
delete = obj.b;
'a' in obj //true
'b' in obj //false
'c' in obj //true
'toString' in obj //true

对于数组而言属性名为1,2,3…
对于delete后的属性名,返回false
对于继承原型链上的属性,返回true

for in
会遍历指定对象上所有属性名

var a = [1,2,3];
for(var key in a){
    if(a.hasOwnProperty(key)){
        console.log(key);
    }
}//1,2,3

for(var key in a){
    console.log(key);
}//1,2,3,has
 var man ={hands:2,legs:2,heads:1};
 //为所有的对象添加clone方法,即给内置原型(object,Array,function)增加原型属性,该方法很强大,也很危险
    if(typeof Object.prototype.clone ==="undefined"){
        Object.prototype.clone = function(){};    
    }
    //
    for(var i in man){
        if (man.hasOwnProperty(i)) { //filter,只输出man的私有属性
            console.log(i,":",man[i]);
        };
    }
    //输出结果为print hands:2,legs:2,heads:1

    for(var i in man) {//不使用过滤
        console.log(i,":",man[i]);
    } //输出结果hands : 2,legs : 2 ,heads : 1 ,clone : function (){} 

    for(var i in man) {
        if(Object.prototype.hasOwnProperty.call(man,i)) { //过滤
            console.log(i,":",man[i]);
        }
    }
   //输出结果为print hands:2,legs:2,heads:1

for of
遍历Array,Map,Set,String,TypedArray,arguments 对象等等,不能遍历{a:”aaa”,b:”bbb”}类型

var a = [1,2,3,4];
for(var key of a){
    console.log(key);
}//1,2,3,4

for(var key of a){
    key +=1;
    console.log(key);
}//2,3,4,5
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值