Why I can't add Symbol.iterator into Object like that
Object.prototype[Symbol.iterator];
let obj = {num: 1 , type : ' :) '}
for (let p of obj) {
console.log(p);
}
// TypeError: obj is not iterable
CodePudding user response:
You have to assign a generator function to Object.prototype[Symbol.iterator]
.
Object.prototype[Symbol.iterator] = function*() {
for (let k in this) {
yield this[k];
}
};
let obj = {
num: 1,
type: ' :) '
}
for (let p of obj) {
console.log(p);
}
CodePudding user response:
Because you didnt actually assign anything to Object.prototype[Symbol.iterator]
- if you do assign an iterator function that does somethign sensible I think it might work as you expected
Object.prototype[Symbol.iterator] = function*(){
for(let entry of Object.entries(this))
yield entry
};
let obj = {num: 1 , type : ' :) '}
for (let [k,v] of obj) {
console.log(k,v);
}
// another way
console.log(...obj)