Iterator迭代器

Iterator迭代器定義

為各種不同的數(shù)據(jù)結構提供統(tǒng)一的訪問機制(即使用for...of訪問),任何數(shù)據(jù)結構,只要部署了Iterator接口,就可以完成遍歷操作。

作用

  • 為各種數(shù)據(jù)結構提供一個統(tǒng)一的簡便的訪問接口
  • 使得數(shù)據(jù)接口的成員能夠按照某種次序排列
  • ES6創(chuàng)造了一種心得遍歷命令for...for循環(huán),Iterator接口主要供for...of消費

遍歷的過程

  • 創(chuàng)建一個指針對象,指向當前數(shù)據(jù)結構的起始位置,也就是說,遍歷器對象本質上就事一個指針對象
  • 第一次調用指針對象的next方法,可以將指針指向數(shù)據(jù)結構的第一個成員
  • 第二次調用指針對象的next方法,指針指向數(shù)據(jù)結果的第二個成員
  • 不斷調用指針對象的next方法,知道它的指向數(shù)據(jù)結構的結束位置

每次調用next返回數(shù)據(jù)結構當前成員的信息,具體返回{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循環(huán)遍歷某個數(shù)據(jù)結構時,該循環(huán)會自動去尋找Iterator接口。只要數(shù)據(jù)結構部署了Iterator接口,就稱這種數(shù)據(jù)結構為可遍歷(iterable)的

在ES6中,默認的Iterator接口部署在數(shù)據(jù)結構的Symbol.iterator屬性,一個數(shù)據(jù)介結構具有Symbol.iterator屬性,就認為時可遍歷的。調用Symbol.iterator方法,就能得到當前數(shù)據(jù)結構 默認的遍歷器生成函數(shù)

例如以下就是一個可遍歷的數(shù)據(jù)結構,因為它就有Symbol.iterator屬性,而且執(zhí)行這個屬性返回的是一個可遍歷的對象。

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

具備默認Iterator接口的數(shù)據(jù)結構

  • Array
  • Map
  • Set
  • String
  • TypedArray
  • 函數(shù)的arguments對象
  • NodeList對象

以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遍歷以上定義的數(shù)組

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

使用場景

解構賦值

對數(shù)組和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'

其他場合

  • for...of
  • Array.from
  • Map(),Set()等
  • Promise.all(),Promise.race()

Iterator接口和Generator函數(shù)

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方法(出錯或有break、continue語句),throw方法主要配合Generator函數(shù)一起使用

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的區(qū)別

for...in的缺點:

  • 數(shù)組的鍵名是數(shù)字,但是使用for...in循環(huán)是以字符串作為鍵名
  • for...in循環(huán)不僅可以遍歷數(shù)字鍵名,也可以遍歷手動添加的其他鍵名,甚至包括原型鏈上的鍵名
  • 某些情況下,for...in會以任意順序遍歷鍵名

for...in主要為遍歷對象而設計,不適用于遍歷數(shù)組

for...of相比之下有以下優(yōu)勢

  • 有著for...in的簡單語法,但是沒有for...in的那些缺點
  • 不用于forEach,它可以使用breakcontinuereturn配合使用,提前結束遍歷
  • 提供了遍歷所有數(shù)據(jù)結構的通過一操作接口
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內容