Symbol.iterator 和 for of

Symbol.iterator and for of are new features of es6 that can set their own iterators for objects

First introduce our for of

var arr = [1,2,3,8,33] for (var i of arr){ console.log(i) } 1 2 3 8 33
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

It 's that simple 
. In fact, it accesses the value attribute in the return value of the arr's iterator calling the next method (don't know what I'm talking about? Keep reading)

Then there is the Symbol.iterator

    var arr = [4,5,6,7,8]; var v = arr[Symbol.iterator](); console.log( v.next() ); console.log( v.next() ); console.log( v.next() ); console.log( v.next() ); console.log( v.next() ); console.log( v.next() ); console.log( v.next() );
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

echo

Object {value: 4, done: false}
Object {value: 5, done: false} Object {value: 6, done: false} Object {value: 7, done: false} Object {value: 8, done: false} //注意这次的done 是 false Object {value: undefined, done: true} Object {value: undefined, done: true} //完成以后再次执行也是true
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

However, object does not support iterators, so we DIY one :)

    var obj ={
        name:1,
        age:13,
        home:"xxxx"
    }
    Object.defineProperty(obj,Symbol.iterator,{ enumerable:false, //是否可枚举 writerable:false, //是否可写 configurable:true, //是否删除 value:function(){ var that = this; var nowindex = 0; var key = Object.keys(that); return { next:function(){ var h = { value:that[key[nowindex]], done:(nowindex+1 >key.length ) } nowindex++; return h } } } }) var i = obj[Symbol.iterator](); console.log( i.next() ); // {value: 1, done: false} console.log( i.next() ); // {value: 13, done: false} console.log( i.next() ); // {value: "xxxx", done: false} console.log( i.next() ); // {value: undefined, done: true}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33

done!

Wait, i.next() has been repeated many times, it is too sb to write like this :( I seem to think of the for of that I just learned, let's try it

    for (var y of obj){
        console.log(y)
    }
    echo
    1 13 xxxx 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

It's so much prettier

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325249837&siteId=291194637