在 ES6 之前的 Typescript 中实现 Iterator<T> 的推荐方法
Recommended way to implement Iterator<T> in Typescript, before ES6
我有一个项目,其中包含许多 类,理想情况下会实现 Iterable<T>
and/or Iterator<T>
接口。但是我似乎找不到这些接口的标准 TypeScript 定义(例如在 typescript-collections 或一些类似的包中)。
我知道这些在 ECMAScript 6 中通过 Symbol.iterator
机制在某种程度上标准化了,但我的目标是 ECMAScript 5 并且在可预见的未来将保持不变。
我能否以某种方式获得这些接口而无需自己定义它们(例如,为了将来与其他模块的兼容性)?
这是 的副本,但这里是 ES5
的答案:
您想使用 ES6
feature:
One addition of ECMAScript 2015 (ES6) is not new syntax or a new
built-in, but a protocol. This protocol can be implemented by any
object respecting some conventions.
There are two protocols: The iterable protocol and the iterator
protocol.
在 ES5
环境中(编译 and/or 运行时),这不是你能做的事情。
话虽这么说,你可以足够接近 because:
An object is an iterator when it knows how to access items from a
collection one at a time, while keeping track of its current position
within that sequence. In JavaScript an iterator is an object that
provides a next() method which returns the next item in the sequence.
This method returns an object with two properties: done and value.
所以你可以 return 一个带有 next
方法的对象,它是一个迭代器:
class Counter /* implements Iterator<number> */ {
private counter = 0;
//public next(): IteratorResult<number> {
public next(): { done: boolean, value: number } {
return {
done: false,
value: this.counter++
}
}
}
let c = new Counter();
console.log(c.next().value); // 0
console.log(c.next().value); // 1
console.log(c.next().value); // 2
注释掉的部分将适用于目标 ES6
,但低于该目标时则无效。
但是如果你的运行时环境确实支持这个功能,那么编译后的js就可以很好地完成工作。
我有一个项目,其中包含许多 类,理想情况下会实现 Iterable<T>
and/or Iterator<T>
接口。但是我似乎找不到这些接口的标准 TypeScript 定义(例如在 typescript-collections 或一些类似的包中)。
我知道这些在 ECMAScript 6 中通过 Symbol.iterator
机制在某种程度上标准化了,但我的目标是 ECMAScript 5 并且在可预见的未来将保持不变。
我能否以某种方式获得这些接口而无需自己定义它们(例如,为了将来与其他模块的兼容性)?
这是 ES5
的答案:
您想使用 ES6
feature:
One addition of ECMAScript 2015 (ES6) is not new syntax or a new built-in, but a protocol. This protocol can be implemented by any object respecting some conventions.
There are two protocols: The iterable protocol and the iterator protocol.
在 ES5
环境中(编译 and/or 运行时),这不是你能做的事情。
话虽这么说,你可以足够接近 because:
An object is an iterator when it knows how to access items from a collection one at a time, while keeping track of its current position within that sequence. In JavaScript an iterator is an object that provides a next() method which returns the next item in the sequence. This method returns an object with two properties: done and value.
所以你可以 return 一个带有 next
方法的对象,它是一个迭代器:
class Counter /* implements Iterator<number> */ {
private counter = 0;
//public next(): IteratorResult<number> {
public next(): { done: boolean, value: number } {
return {
done: false,
value: this.counter++
}
}
}
let c = new Counter();
console.log(c.next().value); // 0
console.log(c.next().value); // 1
console.log(c.next().value); // 2
注释掉的部分将适用于目标 ES6
,但低于该目标时则无效。
但是如果你的运行时环境确实支持这个功能,那么编译后的js就可以很好地完成工作。