Symbol.iterator 為每一個(gè)對象定義了默認(rèn)的迭代器厕倍。該迭代器可以被 [for...of]
循環(huán)使用。
var myIterable = {}
myIterable[Symbol.iterator] = function* () {
yield 1;
yield 2;
yield 3;
};
[...myIterable] // [1, 2, 3]
對象的迭代
var people={
name:'test',
sex:'male',
hobbies:['ball','paint','sing'],
[Symbol.iterator]() {
let index = 0
return {
next: () => {
let keys = Object.keys(this)
return index >= keys.length ? {done: true} : {value: this[keys[index++]], done: false}
}
}
}
};
var obj = people[Symbol.iterator]();
obj.next() //{value: 'test', done: false}
obj.next() //{value: 'male', done: false}
obj.next() //{value: Array(3), done: false}
obj.next() // {done: true}
##第二種
var people={
name:'test',
sex:'male',
hobbies:['ball','paint','sing'],
};
function* itertorObj(obj) {
let keys = Object.keys(obj)
for (let key of keys) {
yield [key, obj[key]];
}
}
var obj = itertorObj(people);
obj.next()