为什么在导入变量之后变为常数?

发布于 2025-02-06 15:32:19 字数 410 浏览 1 评论 0原文

执行index.js后, package.json

{
  "type": "module"
}

users.js

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

export default users;

index.js

import users from './users.js';

users = [];

我遇到了一个错误:

users = [];
      ^

TypeError: Assignment to constant variable.

为什么? 用户明确定义为变量而不是常数。

package.json

{
  "type": "module"
}

users.js

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

export default users;

index.js

import users from './users.js';

users = [];

After executing index.js I get an error:

users = [];
      ^

TypeError: Assignment to constant variable.

Why? The users was clearly defined as a variable not a constant.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

勿忘初心 2025-02-13 15:32:19
  import users from './users.js';

const users = ...

之后无法分配值。它不是完全相同的,因为值可以更改,但是只能从模块内部更改它们。因此,用户内部

let users = [];

export const setUser(newUsers) {
  users = newUsers
}

export {users, setUser);

index.js

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

console.log(users);
console.log(setUser(["a", "b", "c"]));
  import users from './users.js';

is similar to

const users = ...

in that you cannot assign the value afterward. It's not quite the same because the values can change, but they can only be changed from inside the module. so inside users.js

let users = [];

export const setUser(newUsers) {
  users = newUsers
}

export {users, setUser);

index.js

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

console.log(users);
console.log(setUser(["a", "b", "c"]));
莫言歌 2025-02-13 15:32:19

正如@pilchard所解释的那样,要完成我的任务,我需要在模块内更改此数组。那是因为我导入的值仅在模块之外读取。 docs

users.js

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

function emptyUsers() {
    users = [];
}

export { users, emptyUsers };

index.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']

As @pilchard explained, to accomplish my task I need to change this array inside the module. That's because values that I import are read-only outside the module. Docs.

users.js

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

function emptyUsers() {
    users = [];
}

export { users, emptyUsers };

index.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']
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文