[Javascript] Iterate over Object

const [a, b] = {
  a: 3,
  b: 4,
}; 
console.log(a, b); // TypeError: {(intermediate value)(intermediate value)} is not iterable

 

How to make it work without touch original code?

We need to use [Symbol.iterator] for Object.prototype;

Object.prototype[Symbol.iterator] = function() {
    const values = Object.values(this)
    let index = 0
    const len = values.length
    return {
        next() {
           return {
               value: values[index++],
               done: index <= len ? false: true
           }
        }
    }
}
const [a, b] = {
  a: 3,
  b: 4,
};
console.log(a, b);

We can improve this version by knowing const values = Object.values(this)is already a iterable.

 

Object.prototype[Symbol.iterator] = function() {
    const values = Object.values(this)
    return values[Symbol.iterator]()
}
const [a, b] = {
  a: 3,
  b: 4,
};
console.log(a, b);

We can improve this version by using generator.

 

Object.prototype[Symbol.iterator] = function* () {
  yield* Object.values(this);
};

const [a, b] = {
  a: 3,
  b: 4,
};
console.log(a, b);

 

posted @ 2024-11-06 15:53  Zhentiw  阅读(3)  评论(0编辑  收藏  举报