如何使ES6类的迭代器 [英] How to make an iterator out of an ES6 class

查看:158
本文介绍了如何使ES6类的迭代器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用与JS1.7相同的方式使ES6类的迭代器 SomeClass.prototype .__ iterator__ = function(){...} 语法?





以下作品:


$ a


* [Symbol.iterator](){
yield'1';
yield'2';
}

// * generator(){
//}

}

an_instance = new SomeClass() ;
for(let v of an_instance){
console.log(v);
}

WebStorm标志 * [Symbol.iterator]() 具有函数名称预期警告,直接在星号之后,否则这个编译并运行良好。 (注意WebStorm不会生成 * generator()的任何错误。)

解决方案

定义一个合适的迭代器方法。例如:

  class C {
constructor(){this.a = []}
add (x){this.a.push(x)}
[Symbol.iterator](){return this.a.values()}
}


How would I make an iterator out of an ES6 class in the same manner as JS1.7 SomeClass.prototype.__iterator__ = function() {...} syntax?

[EDIT 16:00]

The following works:

class SomeClass {
    constructor() {
    }

    *[Symbol.iterator]() {
        yield '1';
        yield '2';
    }

    //*generator() {
    //}

}

an_instance = new SomeClass();
for (let v of an_instance) {
    console.log(v);
}

WebStorm flags *[Symbol.iterator]() with a 'function name expected' warning directly following the asterix, but otherwise this compiles and runs fine with Traceur. (Note WebStorm does not generate any errors for *generator().)

解决方案

Define a suitable iterator method. For example:

class C {
  constructor() { this.a = [] }
  add(x) { this.a.push(x) }
  [Symbol.iterator]() { return this.a.values() }
}

这篇关于如何使ES6类的迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆