繁体   English   中英

导入后变量变为常量

[英]After the import a variable became a constant

package.json

{
  "type": "module"
}

用户.js

let users = ["Jack", "Mary"];

export default users;

索引.js

import users from './users.js';

users = [];

执行 index.js 后出现错误:

users = [];
      ^

TypeError: Assignment to constant variable.

为什么? users被明确定义为变量而不是常量。

  import users from './users.js';

类似于

const users = ...

因为您不能在之后分配值。 它并不完全相同,因为值可以更改,但它们只能从模块内部更改。 所以在 users.js 里面

let users = [];

export const setUser(newUsers) {
  users = newUsers
}

export {users, setUser);

索引.js

import {users, setUser} from './users.js'

console.log(users);
console.log(setUser(["a", "b", "c"]));

正如@pilchard 所解释的那样,为了完成我的任务,我需要更改模块内的这个数组。 那是因为我导入的值在模块外是只读的。 文件

用户.js

let users = ["Jack", "Mary"];

function emptyUsers() {
    users = [];
}

export { users, emptyUsers };

索引.js

import { users, emptyUsers } from "./users.js"
console.log(users); // ["Jack", "Mary"]

emptyUsers(); // instead of users = [];
console.log(users); // []

users.push('Ricky'); // Also I can still change the values of the imported array
console.log(users); // ['Ricky']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM