我想從另一個檔案中獲取一個(非常大的)陣列,這樣它就不會占用我的主 js 檔案中的空間,但我無法弄清楚,我花了大約 2 - 3 天的時間在網上搜索,但找不到一個答案作業。我已經嘗試了如何訪問在另一個 js 檔案以及許多其他站點中定義的 js 陣列的答案,但沒有任何效果。
// the js file with the array I want
wordList = [
"this",
"is",
"an",
"array"
]
// main js file
const word = wordList[Math.floor(Math.random() * wordList.length)];
任何幫助表示贊賞:) 編輯:如果有幫助,這適用于瀏覽器游戲
uj5u.com熱心網友回復:
您可以使用 export 從第一個檔案中匯出變數。
// example.js
const WordList = [
"this",
"is",
"an",
"array"
]
export { WordList };
然后,使用 import 將變數匯入 main.js 檔案中。
import { WordList } from './example.js'
uj5u.com熱心網友回復:
您需要匯出陣列并將其匯入所需的任何檔案中。匯出/匯入機制的完整細節可以在下一個Stackoverflow 問題中找到
uj5u.com熱心網友回復:
您應該將這兩個腳本都添加到 html。然后,您應該將陣列設為全域:
window.wordList = [
"this",
"is",
"an",
"array"
]
然后在main.js檔案中,您可以像這樣訪問陣列:
const word = window.wordList[Math.floor(Math.random() * wordList.length)];
但請確保在 html 中的 main.js 檔案之前添加帶有陣列的腳本
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/462234.html
標籤:javascript 数组
