javascript - 符号.迭代器: get all the object's properties in iterator object

标签 javascript ecmascript-6 iterator symbols

我目前正在阅读有关 Symbols and Iterators 的内容(ES6 功能),在遇到一个示例后,我尝试使对象可迭代,以便我可以使用 for...of 功能。从这里的几个例子/答案/我检查的文章来看,普通情况下它看起来像这样:

let obj = {
  prop1: 5,
  prop2: 'test',
  prop3: new Date(),
  [Symbol.iterator]: () => ({
  items: obj.items,
  next: function next() {
    return {
        done: this.items.length === 0,
        value: this.items.shift()
      }
  }
  })
};
Object.defineProperty(obj, "items", {
  enumerable: false,
  get: function() {
      let props = [];
      for(let prop in this) if(this.hasOwnProperty(prop)) props.push(this[prop]);
      return props;
  }
});
for(let prop of obj) console.log(prop);

但我发现手动列出迭代器的 items 数组中对象属性的所有值很烦人。 Object.defineProperty 也让人感觉又脏又乱。我有点想汤姆扩展 link 中的示例。是否有一种更智能/更简单的方法来获取迭代器内的所有对象属性(而不是 items: obj.items 和相关的膨胀或手动列出诸如 items: [5, 'test',新日期()])?

最佳答案

您可以在符号迭代器中返回一个生成器:

[Symbol.iterator]:function*(){
    for(value of Object.values(this)){
      yield value;//may extend this to your needs
    }
 }

或者根据您的情况:

[Symbol.iterator]:function*(){
  var i=1;
  while(this["prop"+i]){
      yield this["prop"+i];//may extend this to your needs
      i++;
  }
}

http://jsbin.com/zekunalusi/edit?console

关于javascript - 符号.迭代器: get all the object's properties in iterator object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45102299/

相关文章:

java - 使用 PushbackIterator 合并列表?

collections - 是否可以收集迭代器以向后填充集合?

python - 以可迭代作为参数的函数是否总是接受迭代器?

javascript - babel-eslint 不允许动态导入

javascript - 指定括号内的参数和不指定括号内的参数有什么区别?

javascript - "Warning: Combine this with the previous ' var ' statement",而所说的变量是在 for 循环之后

javascript - 将两个数组中的对象合并为一个

javascript - HTML 5 本地存储

javascript - 创建新类型的输入类型

ecmascript-6 - 使用 let/block 作用域的实际优势是什么?