object 沒有內建的 @@iterator,作者帶我們自己建一個看看
var myObject = {
food: '燃麵',
vegetable: '生菜',
seasoning: '花椒'
};
Object.defineProperty(myObject, Symbol.iterator, {
enumerable: false,
writable: false,
configurable: true,
value: function() {
var _this = this;
var idx = 0;
var keysList = Object.keys( _this );
return {
next: function() {
return {
value: _this[keysList[idx++]],
done: (idx > keysList.length)
};
}
};
}
});
var it = myObject[Symbol.iterator]();
console.log(it.next()); // { value:'燃麵', done:false }
console.log(it.next()); // { value:'生菜', done:false }
console.log(it.next()); // { value:'花椒', done:false }
console.log(it.next()); // { done:true }
for (var v of myObject) {
console.log( v );
} // '燃麵', '生菜', '花椒'