用迭代器 模拟一个for of

 function forOf(arr, cb) {
    //const fun = arr.entries
     const fun = arr[Symbol.iterator]
    if (arr != null && typeof fun !== 'function') {
       throw TypeError("arr is not a iterable")
    }
    let iterator = arr[Symbol.iterator]();
    let obj = iterator.next();
    while (!obj.done) {
      cb(obj.value)
      obj = iterator.next()
    }
  }
 // 测试
  const obj = { k: 1 }
  const obj2 = { k: 2 }
  const wp = new WeakMap([[obj, 1], [obj2, 2]]) //x
  const ws = new WeakSet([[obj, 1], [obj2, 2]])//x
  const map = new Map([[obj, 1], [obj2, 2]])//√
  const set = new Set([[obj, 1], [obj2, 2]])//√
  const arr = Array.from(ws) //√ []

  let ddo = wp
  forOf(ddo, function (val) {
    console.log(val, 'my forOf')
  })
 // for (let i of ddo) {
 //   console.log(i, "for of")
 // }

你可能感兴趣的:(javascript,前端,开发语言)