15-Iterator和for…of循环

一、Iterator(遍历器)概念

 1、js表示“集合”的数据结构,有哪几种?

数组、对象、Map和Set。组合使用他们,会得到自己的数据结构,比如数组里面的item是对象。这就需要统一的接口机制,来处理不同的数据结构。

2、Iterator的作用?

一:为各种数据结构,提供统一的、简便的访问接口;

二:使得数据结构成员能够按照某种次序排序;

三、创建了新的遍历命令,for...of循环。

3、Iterator的遍历过程是什么样的?

(1)创建指针对象,指针对象指向数据结构的起始位置。

(2)第一次调用next方法,指向数据结构的第一个成员。

(3)第二次调用指针对象的next方法,指针就指向数据结构的第二个成员。

(4)不断调用指针对象的next方法,直到它指向数据结构的结束位置。

4、返回什么?
返回value和done值。分别表示成员的值和是否结束的布尔值。

5、你能用遍历器函数自己写一个数据结构出来吗?

无限运行遍历器对象的例子:

var it = idMaker();
it.next().value // 0
it.next().value // 1
it.next().value // 2
// ...
function idMaker() {
  var index = 0;

  return {
    next: function() {
      return {value: index++, done: false};
    }
  };
}

二、默认Iterator接口

6、Iterator接口的目的?

Iterator接口是为了给所有数据结构提供一种统一的访问机制,即for...of循环。当使用for...of循环遍历某种数据结构的时候,该循环会自动去寻找Iterator接口。

7、原生将具备Iterator接口的数据结构有哪些?

数组。

对象没有,因此需要自己在属性上进行定义。

8、为对象添加Iterator接口的例子。 

 let obj = {
      data: ['hello', 'world'],
      [Symbol.iterator](){
          const me = this
          let index = 0
          return{
              next(){
                  if (index < me.data.length){
                      return {
                          value:me.data[index++],
                          done: false
                      }
                  } else {
                      return {value: undefined, done: true}
                  }
              }
          }
      }
  }

8、类数组对象调用Symbol.Iterator方法的例子有哪些?

8、为什么要遍历器接口?

有了遍历器接口,数据结构就可以使用for ...of循环遍历,也可以使用while循环遍历。

三、调用Iterator接口的场合

9、解构赋值和扩展运算符是怎么用到Iterator接口的? 

let set = new Set().add('a').add('b').add('c');

let [x,y] = set;
// x='a'; y='b'

let [first, ...rest] = set;
// first='a'; rest=['b','c'];

10、上述问题有什么意义?

提供了一种渐变机智,可以将任何部署了Iterator接口的数据结构,转化为数组。

11、yield* 

  let test1 = function(i){
      return 1+i
  }
  let generator2 = function* (i){
      i = 2
      yield test1(i);
      yield* [2,3,4];
      yield 5
  }
  var iter = generator2()
  let a = iter.next()
  console.log(a) // {value: 3, done: false}

四、字符串的Iterator接口

12、字符串

字符串是一个类似数组的对象,也有原生Iterator接口

七、for...of循环

13、在数组中的使用?

const arr = ['red', 'green', 'blue'];

for(let v of arr) {
  console.log(v); // red green blue
}

const obj = {};
obj[Symbol.iterator] = arr[Symbol.iterator].bind(arr);

for(let v of obj) {
  console.log(v); // red green blue
}

forof循环可以代替实例的forEach方法。

const arr = [1,2,3]
arr.forEach(function(ele, index){
    console.log('ele-->>',ele) 
    console.log('index-->>',index)
})

14、在数组中for in 与 for of的对比? 

const arr = ['a', 'b', 'c']

for (let index in arr){
    console.log(index) //012
}
for (let item of arr){
    console.log(item) //abc
}

可以看看数组实例的entties和keys方法。这个返回的是键值和键值对。

原文地址:https://www.cnblogs.com/qingshanyici/p/12873343.html