es6 可迭代协议

可迭代协议

可迭代协议允许 JavaScript 对象去定义或者定制它们的迭代行为。

一些内置类型是可迭代,例如 Array,TypeArray,Map,Set,String,在 for…of 结构中可以循环遍历值,而 Object 就不是。

为了变成可迭代对象,一个对象必须实现 @@iterator 方法, 意思是这个对象(或者它原型链 prototype chain 上的某个对象)必须有一个名字是 Symbol.iterator 的属性:

Property Value
[Symbol.iterator] 无参函数,该函数返回一个对象,该对象符合迭代器协议

迭代器协议

迭代器协议定义了一种标准的方式来产生有限或无限序列的值

当一个对象实现了 next() 方法,并且符合如下定义,则该对象就是一个迭代器对象。

属性
next 一个无参函数,返回一个对象,该对象拥有两个属性 done 和 value

done(boolean)

  • 如果迭代器已经到了迭代序列的末尾,done 为 false
  • 如果迭代器还可以产生序列下一个值,done 为 true

value

迭代器返回的任何 JavaScript 值,当 done 为 true,可忽略。

next 方法必须是返回包含 done 和 value 属性的对象,如果非对象(类如 false, undefined)返回,将会抛出 TypeError

例子

可迭代协议例子

自定义一个可迭代对象

const iterableObj = {}
iterableObj[Symbol.iterator] = function* () {
    yield 1
    yield 2
    yield 3
}
console.log([...iterableObj])

接受可迭代对象的内置 APIs

许多 APIs 接受可迭代对象作为参数,例如 Map([iterable]),WeakMap([iterable]),Set([iterable]),WeakSet([iterable])

const myObj = {}
new Map([[1, 'a'], [2, 'b'], [3, 'c']]).get(2)               // "b"
new WeakMap([[{}, 'a'], [myObj, 'b'], [{}, 'c']]).get(myObj) // "b"
new Set([1, 2, 3]).has(3)                                    // true
new Set('123').has('2')                                      // true
new WeakSet(function* () {
    yield {}
    yield myObj
    yield {}
}()).has(myObj)                                              // true

用于可迭代对象的语法

一些语句或者表达式可用于可迭代对象,例如 for…of 循环,spread operator,yield*****,destructuring assignment。

// for...of
for (let i of [1, 2, 4]) {
    console.log(i)
    // 1
    // 2
    // 4
}

// spread operator
console.log([...'abc']) // ["a", "b", "c"]

// yield*
function* gen() {
    yield* ['a', 'b', 'c']
}
console.log(gen().next()) // {value: "a", done: false}

// destructuring assignment
[a, b] = new Set(['a', 'b'])
console.log(a) // a

迭代器协议例子

简单迭代器

function makeIterator(array) {
    let nextIndex = 0
    return {
        next() {
            return nextIndex < array.length ? { value: array[nextIndex++], done: false } : { done: true }
        }
    }
}

const it = makeIterator(['a', 'b'])

console.log(it.next()) // {value: "a", done: false}
console.log(it.next()) // {value: "a", done: false}
console.log(it.next()) // {done: true}

生成器

function* makeSimpleGenerator(arr) {
    let nextIndex = 0
    while (nextIndex < array.length) {
        yield array[nextIndex++]
    }
}

const it = makeSimpleGenerator(['a', 'b'])

console.log(it.next()) // {value: "a", done: false}
console.log(it.next()) // {value: "a", done: false}
console.log(it.next()) // {value: undefined, done: true}

ES6 class

class SimpleIterator {
    constructor(data) {
        this.data = data
        this.index = 0
    }

    [Symbol.iterator]() {
        return {
            next: () => {
                return this.index < this.data.length ? { value: this.data[this.index++], done: false } : { done: true }
            }
        }
    }
}

const simple = new SimpleIterator([1, 3, 9])

for (let i of simple){
    console.log(i) // 1 3 9
}

再谈生成器 generator

从上面的示例可以看出,generator 是比较特殊的,generator 既是一个 生成器对象,又是一个 可迭代对象!

const generatorObj = function* () {
    yield 1
    yield 2
    yield 3
}()

console.log(typeof generatorObj.next) // function

console.log(typeof generatorObj[Symbol.iterator]) // function

console.log(generatorObj[Symbol.iterator]() === generatorObj) // true

猜你喜欢

转载自my.oschina.net/ahaoboy/blog/1628273