簡體   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