![](/img/trans.png)
[英]Is iterating with for..of loop over iterator instead of iterable is legal?
[英]Export iterator from a module to allow iterating over asterisk imports
我有一個包含多個重新導出的索引文件
// things/index.js
export { a } from 'a'
export { b } from 'b'
export { c } from 'c'
現在我想使用另一個文件中的所有內容作為我函數的參數。
這實際上有效:
import * as things from './things'
things[Symbol.iterator] = function* () {
for (let v in this) { yield v }
}
function print(things) {
[...things].forEach(thing => {
console.debug('thing', thing)
});
}
print(things)
// prints:
// thing a
// thing b
// thing c
我想避免以這種方式設置迭代器,而是將它與事物一起導出。 有辦法嗎?
與其使用單獨的命名導出,不如考慮使用單個導出(命名或其他),它是一個具有a
、 b
、 c
屬性的對象,並具有一個Symbol.iterator
屬性:
// things/index.js
import { a } from 'a'
import { b } from 'b'
import { c } from 'c'
export const things = {
a,
b,
c,
[Symbol.iterator]: function* () {
yield a;
yield b;
yield c;
}
};
或者迭代這些值(迭代時不會包含Symbol.iterator
屬性,因為它不可枚舉):
// things/index.js
import { a } from 'a'
import { b } from 'b'
import { c } from 'c'
export const things = {
a,
b,
c,
[Symbol.iterator]: function* () {
yield* Object.values(this);
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.