ES6

Iterator迭代器

2020-06-26  本文已影响0人  ZzzCoder

Iterator迭代器定义

为各种不同的数据结构提供统一的访问机制(即使用for...of访问),任何数据结构,只要部署了Iterator接口,就可以完成遍历操作。

作用

遍历的过程

每次调用next返回数据结构当前成员的信息,具体返回{value, done}两个属性的对象。value表示当前成员的值,done表示遍历是否结束。

模拟Iterator遍历生成器

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

const it = makeIterator([1, 2, 3])

it.next() // { value: 1, done: false }
it.next() // { value: 2, done: false }
it.next() // { value: 3, done: false }
it.next() // { value: undefined, done: true }

默认的Iterator接口

当使用for...of循环遍历某个数据结构时,该循环会自动去寻找Iterator接口。只要数据结构部署了Iterator接口,就称这种数据结构为可遍历(iterable)的

在ES6中,默认的Iterator接口部署在数据结构的Symbol.iterator属性,一个数据介结构具有Symbol.iterator属性,就认为时可遍历的。调用Symbol.iterator方法,就能得到当前数据结构 默认的遍历器生成函数

例如以下就是一个可遍历的数据结构,因为它就有Symbol.iterator属性,而且执行这个属性返回的是一个可遍历的对象。

const obj = {
    [Symbol.iterator]: function () {
        return {
            next: function() {
                return {
                    value: 'coder',
                    done: true
                }
            }
        }
    }
}

具备默认Iterator接口的数据结构

以Array举例

const arr = [1, 2, 3, 4]
const it = arr[Symbol.iterator]()

it.next() // {value: 1, done: false}
it.next() // {value: 2, done: false}
it.next() // {value: 3, done: false}
it.next() // {value: 4, done: false}
it.next() // {value: undefined, done: true}

使用for...of遍历以上定义的数组

for (let value of arr) {
    console.log(value)
}
// 1
// 2
// 3
// 4

为对象添加Iterator接口

const obj = {
    list: ['hello Vue', 'hello React', 'hello ES6'],
    [Symbol.iterator]() {
        const _this = this
        let currentIndex = 0
        return {
            next() {
                if (currentIndex >= _this.list.length) {
                    return {
                        value: void 0,
                        done: true
                    }
                }
                return {
                    value: _this.list[currentIndex++],
                    done: false
                }
            }
        }
    }
}

for (let value of obj) {
    console.log(value)
}

// hello Vue
// hello React
// hello ES6

使用场景

解构赋值

对数组和Set结构进行解构赋值,会默认调用Symbol.iterator方法

const set = new Set(['Vue', 'React', 'ES6'])

const [x, y, z] = set

const [vue, ...rest] = set

扩展运算符

扩展运算符(...)默认调用Iterator接口

const arr = ['Vue', 'React', 'ES6']

function displayName(...args) {
    console.log(...args)
}

displayName(...arr) // Vue React ES6

yield*

yield*后面跟的是一个可遍历的结构,会调用该结构的遍历接口

function *g() {
    yield 'HTML'
    yield* ['Vue', 'React', 'ES6']
    yield 'Webpack'
}

const it = g()

for(let value of it) {
    console.log(value)
}

// 'HTML'
// 'Vue'
// 'React'
// 'ES6'
// 'Webpack'

其他场合

Iterator接口和Generator函数

const obj = {
    * [Symbol.iterator]() {
        yield 'HTML'
        yield* ['Vue', 'React', 'ES6']
        yield 'Webpack'
    }
}

for(let value of obj) {
    console.log(value)
}

// 'HTML'
// 'Vue'
// 'React'
// 'ES6'
// 'Webpack'

遍历器对象的return()和throw()

遍历器对象中除了next方法时必须的,还有returnthrow两个可选方法

提前退出一般使用return方法(出错或有breakcontinue语句),throw方法主要配合Generator函数一起使用

const obj = {
    list: ['hello Vue', 'hello React', 'hello ES6'],
    [Symbol.iterator]() {
        const _this = this
        let currentIndex = 0
        return {
            next() {
                if (currentIndex >= _this.list.length) {
                    return {
                        value: void 0,
                        done: true
                    }
                }
                return {
                    value: _this.list[currentIndex++],
                    done: false
                }
            },
            return() {
                return { value: 'i am a return', done: true }
            }
        }
    }
}

for(let value of obj) {
    console.log(value)
    if (value.includes('React')) {
        break
    }
}

// hello Vue
// hello React
// i am a return

for...offor...in的区别

for...in的缺点:

for...in主要为遍历对象而设计,不适用于遍历数组

for...of相比之下有以下优势

上一篇 下一篇

猜你喜欢

热点阅读