迭代器iterator自定义遍历对象

 

 

 

 

 

let laoshi = {
  name: 'gaoyanfeng',
  student: ['唐僧', '孙悟空', '猪八戒', '沙僧'],
  [Symbol.iterator]() {
    // 索引变量
    let index = 0;
    let _this = this
    return {
      next: function () {
        if (index < _this.student.length) {
          const result = {value: _this.student[index], done: false}
          index++
          return result
        } else {
          return {value: undefined, done: true}
        }
      }
    }
  }
}
for (let v of laoshi) {
console.log(v)
}

 

posted on 2021-01-08 12:00  家有糖果  阅读(114)  评论(0)    收藏  举报

导航