SOURCE

// for of 和 iterable (可迭代的)
// ①、一般的数组和字符串都是支持for of遍历的
let arr = [1,2,3]
for(let val of arr) {
console.log('数组每一项--->',val)
}

let str = '1234'
for (let val of str) {
    console.log('字符串每一项-->',val)
}

// ②、类数组 
let arr1 = {
    0:'iu',
    1:'lisa',
    length:2
}
console.log(Array.from(arr1))  // 需要先将类数组转换为真正的数组再进行迭代
let arr2 = Array.from(arr1)

for(let val of arr2) {
    console.log(val,'--->类数组')
}


// ③、对象类型  (可迭代对象)
let range = {
  from: 1,
  to: 5
};


range[Symbol.iterator] = function(){
    return {
      start:this.from,
      end:this.to,

      next(){
       if(this.start < this.end){
           return {done:false,value:this.start++}
       }else {
            return {done:true}
       }
       
      }
  }
}

for(let val of range) {
    console.log('对象每一项---->',val)
}

// ④、第三种写法的简化
let range1 = {
    from:1,
    to:7,
    [Symbol.iterator]:function(){
       this.current = this.from
       console.log(this,'--->简化')
       return this   // 需要返回一个含有next方法的对象,所以返回自己
    },
    next(){
        if(this.current < this.to) {
            return {done:false,value:this.current++}
        }else {
            return {done:true}
        }
    }
}

for(let val of range1) {
    console.log('简化后的3-->',val)
}


console 命令行工具 X clear

                    
>
console