for...in和for...of

1、for...in

for...in可以迭代对象的可枚举属性

遍历对象时,先顺序遍历对象的以数字为键的属性,然后是顺序遍历以字符为键的属性,而且访问的是属性名

let obj = {
    1 : 1,
    a : 2,
    2 : 3,
    fn : function (){},
    b : 4
}
for(let item in obj){
    console.log(item)
}

for...in可以访问到继承来的属性

    let parent = {
        name : 'father',
        age : 40,
        car : 'BMW'
    }

    let son = Object.create(parent);
    son.name = 'son';
    son.age = 18;

    for(let item in son){
        console.log(item + "  :  " + son[item])
    }

2、for..of

for...of可以遍历具有迭代器(Iterator)的对象,比如Array, Set, Map, arguments,String, DOM中的NodeLIst对象等等。

虽然不能直接遍历普通对象,但还是有办法的,利用Object.keys()方法,把obj的keys生成一个数组,然后遍历

    let obj = {
        first : 1,
        second : 2,
        third : 3
    }

    for(let item of Object.keys(obj)){
        console.log(item + ' : ' + obj[item])
    }

for...of遍历到的是属性值,for...in遍历到的是属性名,而且对于数组,for...of只能遍历到以数字为属性名的属性

    let arr = ['a','b','c'];
    arr.foo = 'foo';
    console.log('for...in');
    for(let item in arr){
        console.log(item)
    }
    console.log('for...of');
    for(let item of arr){
        console.log(item)
    }

for...of只能遍历自身属性

 

 

总结

for...in适合遍历对象

其他数据结构用for...of就好(for...of是es6提供的新方法)

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值