Iterator

2018-08-27  本文已影响0人  陶六六

Iterator和for...of

  1. 可遍历对象条件必备条件:遍历器接口,指针对象,next方法返回值规格
    interface Iterable {
        [Symbol.iterator]() : Iterator,
    }

    interface Iterator {
        next(value?: any) : IterationResult,
    }

    interface IterationResult {
        value: any,
        done: boolean,
    }
  1. Iterator接口调用场合
    • 解构赋值
    • 扩展运算符
    • yield*
    • for..of,
    • Map(),Set(),WeakMap(), WeakSet()
    • Array.from()
    • Promise.all(),Promise.race()
  2. 遍历器对象return()方法,在遍历提前退出(break,error)时触发
  3. 遍历器对象的throw()方法,用于往Generator函数里抛出错误
  4. for...of循环
    • 可以用break,return提前结束循环,forEach不行
    • 数组遍历键名是数字,for...in是字符串,并且for...in会遍历出其他键,包括原型上的键
    • for...in的顺序不能保证
上一篇下一篇

猜你喜欢

热点阅读