如何从索引文件迭代多个导入的模块
How to iterate over multiple imported modules from index file
我有一个名为 Polygons
的目录,我在其中创建了一个 index.js
文件以从该目录导出所有文件。它看起来像这样:
export {default as europe} from './europe'
export {default as northAmerica} from './northAmerica'
europe
文件像这样导出变量:
export default europe;
在我想使用这些变量的文件中,我像这样导入它们:
import * as regions from './Polygons'
我现在想以某种方式迭代这些导入,有什么方法可以做到这一点吗?
我试过:
for (const element of regions) {
console.log(element);
}
但是,然后我得到:
Uncaught (in promise) TypeError: Invalid attempt to iterate non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.
它是一个对象,所以for..of会失败但是你可以用Object.keys
或Object.values
把它转换成数组然后得到结果。
下面是一个执行相同操作的示例代码:
keys = Object.keys(React)
for (const key of keys) {
console.log(key, React[key])
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
希望对您有所帮助。恢复任何 doubts/clarifications.
我有一个名为 Polygons
的目录,我在其中创建了一个 index.js
文件以从该目录导出所有文件。它看起来像这样:
export {default as europe} from './europe'
export {default as northAmerica} from './northAmerica'
europe
文件像这样导出变量:
export default europe;
在我想使用这些变量的文件中,我像这样导入它们:
import * as regions from './Polygons'
我现在想以某种方式迭代这些导入,有什么方法可以做到这一点吗?
我试过:
for (const element of regions) {
console.log(element);
}
但是,然后我得到:
Uncaught (in promise) TypeError: Invalid attempt to iterate non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.
它是一个对象,所以for..of会失败但是你可以用Object.keys
或Object.values
把它转换成数组然后得到结果。
下面是一个执行相同操作的示例代码:
keys = Object.keys(React)
for (const key of keys) {
console.log(key, React[key])
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
希望对您有所帮助。恢复任何 doubts/clarifications.