Javascript对象如何与for语句进行迭代?

cic*_*ino 12 javascript debugging iterator ecmascript-6 for-of-loop

我想设置options[Symbol.iterator]属性,以便使用for...of语句迭代我创建的简单对象:

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


for(let p of options){
  console.log(`Property ${p}`);
};
Run Code Online (Sandbox Code Playgroud)

但是这段代码给了我以下错误:

 array.html:72 Uncaught TypeError: options[Symbol.iterator] is not a function
Run Code Online (Sandbox Code Playgroud)

如何在上面的简单对象上设置正确的迭代器函数?

解决了

 // 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};
  };
Run Code Online (Sandbox Code Playgroud)

for...of我现在可以迭代使用我的对象上的语句:

 for(let property of options){
   console.log(`Properties -> ${property}`);
 }
Run Code Online (Sandbox Code Playgroud)

Leo*_*tny 24

要使用for...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
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

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

另外,您可以将您的对象转换为迭代阵列使用Object.keys,Object.valuesObject.entries(ES7).

  • @Bergi 不,它不起作用。你必须返回一个迭代器,而不是一个可迭代的对象。要重用`Object.entries` 中的迭代器,你应该`return Object.entries(this)[Symbol.iterator]()`。 (2认同)
  • @Bergi noop, [`Object.entries`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries) 返回一个普通的 JS 数组 `[key,值]` 对。 (2认同)

Dmi*_*riy 10

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

    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}`);
    }
Run Code Online (Sandbox Code Playgroud)


hal*_*ons 5

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

for(let k of Object.keys(options)) {
  console.log(`Property ${k}, ${options[k]}`);
};
Run Code Online (Sandbox Code Playgroud)