实现对象的Symbol.itertor

第一种:

var people={
  name:'test',
  sex:'male',
  hobbies:['ball','paint','sing'],
  [Symbol.iterator]() {
    let index = 0
    return {
      next: () => {
        let keys = Object.keys(this)
        return index >= keys.length ? {done: true} : {value: this[keys[index++]], done: false}
      }
    }
  }
};

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

第二种:

var people={
  name:'test',
  sex:'male',
  hobbies:['ball','paint','sing'],
};

function* itertorObj(obj) {
  let keys = Object.keys(obj)
  for (let key of keys) {
    yield [key, obj[key]];
  }
}

for(let [key, value] of itertorObj(people)){
  console.log(key, value)
}

 

上一篇:Bean的作用域及自动装配


下一篇:Spark SQL 及其DataFrame的基本操作