只需添加 TS 应该理解结构的类型注释即可。它还不能从集合中推断出来。
const array: [string, number][] = [['a', 1], ['b', 2]];
for (const [x, y] of array) {
y + 1;
}
另外我想提一下,在处理二维关联时,我认为更好的数据结构是 Map:
const myMap = new Map<string, number>([['a', 1], ['b', 2]]);
for (const [x, y] of [...myMap]) {
console.log(y + 1);
}
高级:自定义迭代
如果元组的逻辑是一致的,那么您可以使用以下方法创建自己的可迭代对象Symbol.iterator
著名符号:
class TupleMaker implements Iterable<[string, number]> {
private next = 0;
constructor(private endsAt: number = 0) {}
private increment(): void {
this.next++;
}
*[Symbol.iterator](): Generator<[string, number]> {
const alpha = Array.from(Array(26)).map((e, i) => i + 65);
const alphabet = alpha.map((x) => String.fromCharCode(x).toLocaleLowerCase());
while (this.next < this.endsAt) {
yield [alphabet[this.next], this.next + 1];
this.increment();
}
}
}
for (const [x, y] of new TupleMaker(13)) {
console.log(y + 1);
}
它们也可以是异步的,使用Symbol.asyncIterator