This question already has answers here:
Using Objects in For Of Loops

(14个回答)


4年前关闭。




我想设置options[Symbol.iterator]属性,以便迭代使用for...of语句创建的简单对象:
options = {
  male: 'John',
  female: 'Gina',
  rel: 'Love'
};


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

但是这段代码给了我以下错误:
 array.html:72 Uncaught TypeError: options[Symbol.iterator] is not a function

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


 // 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};
  };

现在可以在我的对象上使用for...of语句进行迭代了:
 for(let property of options){
   console.log(`Properties -> ${property}`);
 }

最佳答案

要使用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
    }
  }
}

不过,在大多数情况下,最好使用普通的for...in循环遍历对象。

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

关于javascript - for…of语句如何使Javascript对象变得可迭代? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35819763/

10-12 00:02
查看更多