for...in for...of 傻傻分不清楚

先看个例子

const arr = ["red","green","blue"];
// 0 "red"
// 1 "green"
// 2 "blue"
for(let index in arr){
    console.log(index,arr[index]);
}

// "a" "hello"
// "b" "world"
const obj = {a:"hello",b:"world"};
for(let key in obj){
    console.log(key,obj[key]);
}

// "red"
// "green"
// "blue"
for(let item of arr){
    console.log(item);
}

for(let item of obj){
    console.log(item);//报错
}

在这里插入图片描述
数组和对象都可以使用for...in遍历;数组可以使用for...of遍历,但对象不能使用for...of遍历。
结论暂且得到了,那么问题来了:对象为什么不能使用for...of遍历?
报错信息说:“obj is not iterable”。
在这里插入图片描述
瞧,数组具备Symbol.iterator属性,所以iterable,能使用for...of遍历;对象不具备Symbol.iterator属性,所以not iterable,不能使用for...of遍历。

arr[Symbol.iterator]是一个用来生成遍历器的函数。
const it = arr[Symbol.iterator](),就得到了遍历器it,实际是一个指针。
it.next();调用遍历器的next方法,指针指向了arr的第一个成员"red"
it.next();继续调用next方法,指针指向了arr的第二个成员"green"
it.next();继续调用next方法,指针指向了arr的最后一个成员"blue"
it.next();第四次调用next方法,指针指向结束位置,遍历结束。
在这里插入图片描述
在这里插入图片描述
好吧,既然只要有Symbol.iterator属性,且Symbol.iterator生成的遍历器具有next方法,就能够使用for...of进行遍历,那我们就来试试改造对象吧。

const obj = {
    data:["hello","world"],
    [Symbol.iterator]:function(){
        return {
            next:function(){
                var value = this.data.shift();
                var done = !value;
                return {
                    value,
                    done
                }
            }.bind(this)
        }
    }
}
//测试代码1
for(let item of obj){
    console.log(item);//输出 "hello" "world"
}
//测试代码2
const it = obj[Symbol.iterator]();
console.log(it.next());
console.log(it.next());
console.log(it.next());

注:使用Symbol定义对象属性时,Symbol必须放在方括号中。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值