是否可以使用下拉选项创建数组的动态常量名称?
Import {array1, array2, array3} from './myfilesystem/arrays';
const somename = array1;
您需要:
-
将数组放入一个键控对象中。
-
将键放在下拉列表中。
-
将选定的键放入变量中。
-
使用该变量的值查找对象中的数组。
像这样:
const arrays = {
array1: [...],
array2: [...],
array3: [...]
}
const optionsForDropdown = Object.keys(arrays) // ["array1", "array2",...]
function returnSelectedArray(selectedKey) {
return arrays[selectedKey]
}
因此,如果您拨打returnSelectedArray("array1")
或拨打:
const key = "array1"
returnSelectedArray(key)
您将取回arrays.array1
。
import * as arr from '..pathname'
// ..and somewhere in your code..
const someArray = arr.array1
这就是事实吗?
导入/导出:
从文件导出,具有许多语法变体
// explicit exports
export const PI = 3.14159
export const cylinderVolume = (r, h) => {....}
//export as an object..
const PI = 3.14159
const cylinderVolume = (r, h) => {....}
export { PI, cylinderVolume }
// default export
export default PI = 3.14159
export const cylinderVolume = (r, h) => {....}
imports
// importing explict exports
import { PI, cylinderVolume } from 'path'
//importing default and explict exports(PI is default and cylinderVolume is explict)
import PI, { cylinderVolume } from 'path'
// importing as whole..
import * as shape from 'path'
// useage..
const cylinderSurfaceArea = (r, h) => 2*shape.PI*r ( r + h )
从另一个文件重新导出。。
export { cylinderVolume } from 'path'
// re-exporting as default..
export { default as PI } from 'path'
比较用例中对大小的一些影响:
import _ from 'lodash' // use case..
import * as shape from 'path' // same effect..
这将导入整个模块,并对项目规模产生巨大影响。然而,如果我们使用像lodash这样的libs,这是他们推荐的方式。
import { get, has } from 'lodash'
import { PI, cylinderVolume } from 'path'
令人惊讶的是,与上面的语法相比,这并没有太大的大小差异。
摇树
现代构建工具(webpack和其他工具(将模块捆绑在一起并进行优化,以加快加载和删除未使用的内容。
因此,为了最大限度地减少对大小的影响,建议使用语法
import get from 'lodash/get'
但是,当我们必须导入一大堆东西时,这是不实用的(或者出于可读性的考虑,推荐/理想(。。