【发布时间】:2017-07-24 18:57:10
【问题描述】:
Please find the complete code example in action here.
我正在尝试将生成器用作迭代器并将其与 toString 中的 for..of 循环结合起来,但不知何故它不起作用。
这是我的(生成器)迭代器的样子 -
*[Symbol.iterator]() {
let temp = this.head;
while (temp) {
yield temp.item;
temp = temp.next;
}
}
然后我尝试在toString 方法中使用它,如下所示 -
[Symbol.toStringTag]() {
for (const temp of this) {
return `${temp} -> `;
}
}
我想使用for..of 循环和this 引用应该调用迭代器,但它没有。这可以通过控制台日志中缺少 Iterator called 语句来观察,并且使用默认的 toString 打印对象。
我有什么遗漏吗?
【问题讨论】:
-
Symbol.toStringTag与toString不同。你想达到什么目的? -
我正在尝试提供
toString实现。我认为这些与Mozilla doc 声明它是由Object.prototype.toString()方法在内部调用的相同。即使我将其更改为普通的toString我也会得到相同的行为。我希望得到1 -> 2 -> 3之类的列表表示形式。
标签: javascript ecmascript-6 es6-class