19

I would like to set the options[Symbol.iterator] property in order to iterate on the simple objects I create with the for...of statement :

options = {
  male: 'John',
  female: 'Gina',
  rel: 'Love'
};


for(let p of options){
  console.log(`Property ${p}`);
};

But this code gives me the following error:

 array.html:72 Uncaught TypeError: options[Symbol.iterator] is not a function

How I can set the right iterator function on a simple object as above?

Solved

 // define the Iterator for the options object 
 options[Symbol.iterator] = function(){

     // get the properties of the object 
     let properties = Object.keys(this);
     let count = 0;
     // set to true when the loop is done 
     isDone = false;

     // define the next method, need for iterator 
     let next = () => {
        // control on last property reach 
        if(count >= properties.length){
           isDone = true;
        }
        return {done:isDone, value: this[properties[count++]]};
     }

     // return the next method used to iterate 
     return {next};
  };

And I can use the for...of statement on my object now iterable :

 for(let property of options){
   console.log(`Properties -> ${property}`);
 }
4

3 回答 3

30

要使用循环,您应该使用keyfor...of为您的对象定义一个适当的迭代器。[Symbol.iterator]

这是一种可能的实现:

let options = {
  male: 'John',
  female: 'Gina',
  rel: 'Love',
  [Symbol.iterator]: function * () {
    for (let key in this) {
      yield [key, this[key]] // yield [key, value] pair
    }
  }
}

不过,在大多数情况下,使用普通循环来迭代对象会更好for...in

或者,您可以使用Object.keys,Object.valuesObject.entries(ES7) 将对象转换为可迭代数组。

于 2016-03-05T21:04:39.693 回答
13

如果您不想使用生成器语法,可以使用另一种方式定义迭代器函数。

    var options = {
        male: 'John',
        female: 'Gina',
        rel: 'Love',
        [Symbol.iterator]: function () {
            var self = this;
            var values = Object.keys(this);
            var i = 0;
            return {
                next: function () {
                    return {
                        value: self[values[i++]],
                        done: i >= values.length
                    }
                }
            }
        }
    };

    for (var p of options) {
        console.log(`Property ${p}`);
    }
于 2016-03-05T21:33:43.153 回答
5

普通对象(options在这种情况下)在 ES6 中是不可迭代的。您需要为您的对象定义一个迭代器或执行以下操作:

for(let k of Object.keys(options)) {
  console.log(`Property ${k}, ${options[k]}`);
};
于 2016-03-05T21:09:36.100 回答