ES6 自定义迭代器

来源:互联网 发布:java long 类型长度 编辑:程序博客网 时间:2024/06/04 00:23

ES6添加了迭代器,比如说for,of遍历的时候,就是使用内置的迭代器

比如:

const digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];for (const digit of digits) {  console.log(digit);}
0 1 2 3 4 5 6 7 8 9 

因此我们可以把内置的迭代器取出来,对迭代器进行遍历,看看迭代器的状态

const digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];const arrayIterator = digits[Symbol.iterator]();console.log(arrayIterator.next());console.log(arrayIterator.next());console.log(arrayIterator.next());
Object {value: 0, done: false}Object {value: 1, done: false}Object {value: 2, done: false}
  • value:表示对象中值序列的下个值的数据
  • done:表示迭代器是否已循环访问完值序列的布尔值
    • 如果 done 为 true,则迭代器已到达值序列的末尾处。
    • 如果 done 为 false,则迭代器能够生成值序列中的另一个值。

那么对于没有内置迭代器的对象怎么办,比如说

const james = {    name: 'James',    height: `5'10"`,    weight: 185};

如何进行遍历?

此时需要自定义迭代器,下面给出一个自定义迭代器的实现

const james = {    name: 'James',    height: `5'10"`,    weight: 185};james[Symbol.iterator]= function () {  var keys = Object.keys(this);  var index = 0;  return {    next: function () {      return {        value: james[keys[index]], key:keys[index] ,done: ++index >= keys.length      };    }  }}const iterator = james[Symbol.iterator]();//console.log(iterator.next()); // 'James'console.log(iterator.next()); // `5'10`console.log(iterator.next()); // 185
{ value: 'James', key: 'name', done: false }{ value: '5\'10"', key: 'height', done: false }{ value: 185, key: 'weight', done: true }
原创粉丝点击