【问题标题】:How to access an array stored in a different js file如何访问存储在不同js文件中的数组
【发布时间】: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 并将其像 &lt;%= include harryText %&gt; 一样包含在生成器数组中,这是无效的代码。

是否可以从另一个文件调用一个数组并将其存储在另一个数组中?有谁知道这个问题的解决方案吗?

是的,我知道哈利波特 Ipsum 已经存在。这只是虚拟文本。

【问题讨论】:

  • 您似乎从未在 harryText.js 中声明过 harryText 变量。你刚开始使用它,没有先说constlet
  • 即使在 harryText.js 中包含 const 或 let 后,它仍然显示 ReferenceError: harryText is not defined

标签: javascript arrays node.js express


【解决方案1】:

Javascript 文件是相互隔离的。要共享通用代码,您总是需要requiremodule.exports

所以你用module.exports = harryText做正确的事

然后你需要requiregenerator.js中的那个文件

const harryText = require("./harryText");
function GenerateNewText(){
this.sentences = [
    harryText,
    ron = [
       "I am a Weasley",
       "Gryffindor",
       "Quidditch keeper"
    ]
  ]
}

【讨论】:

  • 您好,我在 generator.js 中确实需要它,但它仍然显示 harryText 未定义。
  • 没关系,我现在明白你的意思了。我有一个 const loremIpsum = new GenerateNewText() 没有包含在我的 OP 中,所以当我看到你的答案时,我错误地包含了 const harryText = require("./harryText"),就像你的例子一样,但是在我的 const loremIpsum 下,而不是在它上面。因此,我不知不觉地创建了一个范围界定问题。无论如何,你的回答有帮助。谢谢你。
【解决方案2】:

如果您使用的是 ES6,您可以执行以下操作。

//file1.js
  export const harryText = [
     "I am the chosen one",
     "I am a Gryffindor",
     "I am a boy"
  ]

//file2.js
  import {harryText} from './file1.js';
  // use variable here 

【讨论】:

  • 如果您直接在浏览器中运行此代码,它将无法工作。你需要 babel 来编译它。如果您的环境设置不支持 es6,这将不起作用。
【解决方案3】:

更新 2/20/19 16:15 我得到了 harryText is not defined 错误,因为我一直愚蠢地将变量定义在错误的位置!首先我在function GenerateNewText 之外定义它,然后我尝试在this.sentence 内部定义它。相反,我应该在function GenerateNewTextthis.sentence 之外定义它,就像这样

function GenerateNewText(){
  const harryText = require("./harryText");
  const ronText = require("./ronText");
  this.sentences = [
    harryText,
    ronText
  ]
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-01
    • 2018-05-28
    • 2022-12-18
    • 2019-10-16
    • 1970-01-01
    • 2021-07-25
    相关资源
    最近更新 更多