【发布时间】:2019-07-14 17:17:10
【问题描述】:
我正在尝试创建自己的 lorem ipsum 应用程序,并且我想通过将我的单词库存储在其他文件中来保持我的代码干净。如何访问存储在不同 JS 文件中的数组?例如,我不想硬编码harry = ["", "", ""],而是想将该数据存储在不同的文件中,然后将该文件调用到数组中。
// generator.js
function GenerateNewText(){
this.sentences = [
harry = [
"I am the chosen one!",
"Boy wizard",
"Quidditch seeker"
ron = [
"I am a Weasley",
"Gryffindor",
"Quidditch keeper"
]
]
}
GenerateNewText.prototype.getRandomSentence = function() {
let randomSentence = this.sentences[0][Math.floor(Math.random() * this.sentences.length)]
return randomSentence;
}
目前,我有一个 harryText.js,其中包含
// harryText.js
harryText = [
"I am the chosen one",
"I am a Gryffindor",
"I am a boy"
]
module.exports = harryText;
但在我的 generator.js 中执行此操作会显示 harryText is not defined
function GenerateNewText(){
this.sentences = [
harryText, <---- error here
ron = [
"I am a Weasley",
"Gryffindor",
"Quidditch keeper"
]
]
}
我试着像这样要求它
const harryText = require("./harryText.js")
问题仍然存在。我猜是范围问题?
我尝试安装 ejs 并更改 harryText.ejs 并将其像 <%= include harryText %> 一样包含在生成器数组中,这是无效的代码。
是否可以从另一个文件调用一个数组并将其存储在另一个数组中?有谁知道这个问题的解决方案吗?
是的,我知道哈利波特 Ipsum 已经存在。这只是虚拟文本。
【问题讨论】:
-
您似乎从未在
harryText.js中声明过harryText变量。你刚开始使用它,没有先说const或let。 -
即使在 harryText.js 中包含 const 或 let 后,它仍然显示 ReferenceError: harryText is not defined
标签: javascript arrays node.js express