Symbol.iterator 和 for of 是es6的新特性 可以为对象设置 自己的迭代器
首先介绍我们的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
就是这么简单
这里呢其实访问了 arr的迭代器调用next的方法的返回值中的value属性 (不知道我在说什么?继续往下看)
然后就是 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
然而object 是不支持迭代器的,于是我们DIY一个:)
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!
等等 i.next()重复了好多次,这样写也太sb了:( 我好像想到了刚刚学的 for of 让我们来试试
for (var y of obj){
console.log(y)
}
echo
1 13 xxxx
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
这样就漂亮多了