Javascript 如何更改ES6导入的阵列
所以我有一个使用ES6模块构建的应用程序,我想清除一个作为模块导入到一个文件中的数组,然后从另一个文件添加到该数组中。推送到数组可以很好地工作,但是我不能在delete函数中清空数组。在调试方面,函数被调用,我没有得到任何错误,但是数组没有被清除 如果数组与清除函数包含在同一模块中,则该数组将清除 下面是一个例子Javascript 如何更改ES6导入的阵列,javascript,arrays,ecmascript-6,import,module,Javascript,Arrays,Ecmascript 6,Import,Module,所以我有一个使用ES6模块构建的应用程序,我想清除一个作为模块导入到一个文件中的数组,然后从另一个文件添加到该数组中。推送到数组可以很好地工作,但是我不能在delete函数中清空数组。在调试方面,函数被调用,我没有得到任何错误,但是数组没有被清除 如果数组与清除函数包含在同一模块中,则该数组将清除 下面是一个例子 module_1.js export let array = []; ///////////////////////////////////////////////
module_1.js
export let array = [];
//////////////////////////////////////////////////
module_2.js
import { array } from './module_1.js';
export const func = () => {array.push('hello')};
//////////////////////////////////////////////////
module_3.js
import { array } from './module_1.js';
export const clear = () => {
let array = [];
}
/////////////////////////////////////////////////
module_4.js
import { array } from './module_1.js';
import { func } from './module_2.js';
import { clear } fromt './modeule_3.js';
button.addEventListener('click', func);
button.addEventListener('click', clear);
在module_3.js中,您将数组变量重新定义为let,这将定义一个作用于clear函数的局部变量,删除let将得到预期的结果
export const clear = () => {
array = [];
};
您不能在声明模块的外部重新分配模块变量,即使是使用
let
或var
定义的
那么这个,
//module1.js
导出let foo='bar'
foo='baz'
//module2.js
从“./module1.js”导入{foo}
console.log(foo)//baz
…有效,而这:
//module1.js
导出let foo='bar'
//module2.js
从“./module1.js”导入{foo}
foo='baz'//TypeError
console.log(foo)
…没有
但是,对象的变异仍然是允许的,这就是为什么.push()
可以在第二个模块中工作的原因
要解决此问题,您必须:
长度设置为零来清空数组,但这仍然会从外部修改模块的数据,这不是最佳做法
//module_3.js
import { array } from './module_1.js';
export const clear = () => {
array.length = 0;
}
//module_1.js
export let array = [];
export const func = () => {
array.push('hello')
};
export const clear = () => {
array = [];
}
//module_1.js
export let array = [];
import {func as _func} from './module_2.js';
export const func = () => _func(array)
import {clear as _clear} from './module_3.js';
export const clear = () => _clear(array)
我确实这么想,但是当我尝试导入数组并在没有声明的情况下调用它时,我得到了。未捕获类型错误:常量变量赋值。非常感谢。无论如何,今天早些时候我还是设法找到了解决办法。数组存储在一个对象中,所以我发现我可以像这样清除它们<代码>某个对象[数组]=[]代码>
//module_1.js
export let array = [];
import {func as _func} from './module_2.js';
export const func = () => _func(array)
import {clear as _clear} from './module_3.js';
export const clear = () => _clear(array)
//module_2.js
export const func = (array) => {
array.push('hello')
};
//module_3.js
export const clear = (array) => {
array.length = 0;
}
//module_4.js
import { func, clear } from './module_1.js';
button.addEventListener('click', func);
button.addEventListener('click', clear);