ES6对象中实现Symbol.iterator接口

可以实现自定义规则的对对象内部数据的遍历

var people={
    name:'test',
    sex:'male',
    hobbies:['ball','paint','sing'],
    [Symbol.iterator](){
        const _this=this;
        let index=0;
        return {
            next(){
                if(index<_this.hobbies.length){
                    return {
                        value:_this.hobbies[index++],
                        done:false
                    }
                }else{
                    return {
                        value:undefined,
                        done:true
                    }
                }
                //index++;
            }
        }
    }
};

for(let h of people){
    console.log(h)
}

版权声明:本文为weixin_43847545原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。