Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ES6复习-Iterator 迭代器 #20

Open
Jsmond2016 opened this issue Mar 20, 2022 · 0 comments
Open

ES6复习-Iterator 迭代器 #20

Jsmond2016 opened this issue Mar 20, 2022 · 0 comments
Labels
手写系列 各种手写原理 面试 面试题系列

Comments

@Jsmond2016
Copy link
Owner

Iterator 概念:iterator是一种接口机制,为各种不同的数据结构提供统一的访问机制

作用

  • 为各种数据结构,提供一个统一的、简便的访问接口;
  • 使得数据结构的成员能够按某种次序排列
  • ES6 创造了一种新的遍历命令for...of循环,Iterator接口主要供 for...of消费。

工作原理

  • 创建一个指针对象(遍历器对象),指向数据结构的起始位置
  • 第一次调用 next 方法,指针自动指向数据结构的第一个成员
  • 接下来不断调用 next 方法,指针会一直往后移动,直到指向最后一个成员
  • 每调用next方法返回的是一个包含value和done的对象
{
  value: 当前成员的值,
  done: 布尔值
}
  • value表示当前成员的值,done对应的布尔值表示当前的数据的结构是否遍历结束。
  • 当遍历结束的时候返回的value值是undefined,done值为false

自己实现一个 iterator

看代码:

 /**
  * 自己实现一个 迭代器
  *
  * @param {*} source
  * @returns
  */
 function myIterator(source) {
   let nextIndex = 0
   return {
     next: function() {
       return nextIndex < source.length ? {
          value: source[nextIndex++],
          done: false,
        } 
        : {
          value: undefined,
          done: true,
        }
     }
   }
 }

 // test iterator

 const arr = [1,2,3, {name: 'Tom', age: 18}, 'hello, tom']
 const testIteratorObj = myIterator(arr)
 console.log(testIteratorObj.next())
 console.log(testIteratorObj.next())
 console.log(testIteratorObj.next())
 console.log(testIteratorObj.next())
 console.log(testIteratorObj.next())
 console.log(testIteratorObj.next())

// 结果:
// { value: 1, done: false }
// { value: 2, done: false }
// { value: 3, done: false }
// { value: { name: 'Tom', age: 18 }, done: false }
// { value: 'hello, tom', done: false }
// { value: undefined, done: true }

拓展

以下类型数据原生具备 iterator 接口——可以用 for...of 遍历

  • Array
  • arguments
  • Set 容器
  • Map 容器
  • String

注意: 没有 Object,对象没有 iterator 接口

const obj = {
  name: 'Tom',
  age: 18
}
for (let i of obj) {
  console.log(obj[i])
}
//TypeError: obj is not iterable

这里,说明下 arguments 的用法,看代码:

// 不用定义参数,使用 arguments 获取到
function fun() {
  for (let i of arguments) {
    console.log(arguments[i])
  }
}

fun(1, 'b', 3, {name: 'Tom'}, false)
// 结果
// 1
// b
// 3
// { name: 'Tom' }
// false

拓展

对于 拓展运算符(... 运算符) 和 解构赋值,本质上还是 iterator 的使用,它们会默认去调用 iterator 接口

更多学习资料,参考:

@Jsmond2016 Jsmond2016 added 手写系列 各种手写原理 面试 面试题系列 labels Mar 20, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
手写系列 各种手写原理 面试 面试题系列
Projects
None yet
Development

No branches or pull requests

1 participant