Skip to content

Instantly share code, notes, and snippets.

@wowiwo1
Created October 31, 2015 07:40
Show Gist options
  • Save wowiwo1/692214aea0a4b28a4e40 to your computer and use it in GitHub Desktop.
Save wowiwo1/692214aea0a4b28a4e40 to your computer and use it in GitHub Desktop.
var myObject = {
a: 2,
b: 3
};
Object.defineProperty( myObject, Symbol.iterator, {
enumerable: false,
writable: false,
configurable: true,
value: function() {
var o = this;
var idx = 0;
var ks = Object.keys( o );
return {
next: function() {
return {
value: o[ks[idx++]],
done: (idx > ks.length)
};
}
};
}
} );
// iterate `myObject` manually
var it = myObject[Symbol.iterator]();
it.next(); // { value:2, done:false }
it.next(); // { value:3, done:false }
it.next(); // { value:undefined, done:true }
// iterate `myObject` with `for..of`
for (var v of myObject) {
console.log( v );
}
// 2
// 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment