【问题标题】:Why is const variable localQuotes not defined in this random quotes generator?为什么这个随机引号生成器中没有定义 const 变量 localQuotes?
【发布时间】:2021-12-29 02:39:34
【问题描述】:

问题在这里解释得更清楚: 我正在使用 JavaScript 创建一个简单的随机报价生成器。我在一个名为“quotes.js”的文件中的数组中有数百个引号,然后是使它在一个名为“script.js”的文件中工作的实际函数,它们都链接到一个“index.html”页面。我在“script.js”页面中遇到错误,该页面应该允许从 quotes.js 中的数组中获取随机引用,并在每次刷新页面时在屏幕上显示该随机引用(您会看到在控制台中引用而不是实际页面)。有人可以向我解释为什么会出现此错误以及如何定义变量 localQuotes 吗?

这是我在 Chrome 的开发者工具控制台选项卡中遇到的错误:

未捕获的 ReferenceError:未定义 localQuotes 在 newQuote (script.js:3) at script.js:7 newQuote @ script.js:3(匿名)@ script.js:7

这是我的 script.js 代码:

function newQuote() {
    const quote = localQuotes[Math.floor(Math.random() * localQuotes.length)];
    console.log(quote); 
}

newQuote(); 

这里是quotes.js 中数组的更短版本:

 const localQuotes = [
 {
    text: 'The greatest remedy for anger is delay.',
    author: 'Seneca',
  },
  {
    text: 'Growth itself contains the germ of happiness.',
    author: 'Pearl Buck',
  },
  {
    text: "You can do what's reasonable or you can decide what's possible.",
    author: null,
  },
];

最后是我在 html 文件中链接的 JavaScript:

<!-- Script -->
    <script>src="quotes.js"</script>
    <script src="script.js"></script>

【问题讨论】:

    标签: javascript variables undefined uncaught-reference-error


    【解决方案1】:

    您的quotes.js 将需要授予对变量的全局访问权限才能使其工作。你应该这样做:

    window.localQuotes = {...}
    

    哦,你的脚本标签是错误的,你有一个错字,我在写问题时预计它是一个错字,所以如果它仍然不起作用,请修复那个错字。

    【讨论】:

    • 我对 JavaScript 和一般编程非常陌生。你能更详细地解释一下吗?什么进入{。 . .}?它是在数组的末尾还是开头?我认为“窗口”与在屏幕上显示它有关。我只需要它显示在控制台选项卡中。抱歉,如果我在这里完全偏离基地,我对此很陌生。
    • ... 代表您的报价对象。所以你只需要将const localQuotes 替换为window.localQuotes - 这是因为script.js 无法访问quotes.js 内部的变量,但是你可以通过将它们添加到全局窗口对象来共享变量。
    • 很好地抓住了错字!谢谢
    • 好吧,错误消失了,但现在“控制台”选项卡中没有显示任何内容。有任何想法吗?我把代码改成这样:window.localQuotes = [ { text: '天才是百分之一的灵感和百分之九十九的汗水。', author: 'Yogi Berra', }, ];
    • 当我在编辑器中将鼠标悬停在 window.localQuotes 上时出现此错误:属性 'localQuotes' 在类型 'Window & typeof globalThis'.ts(2339) 上不存在
    【解决方案2】:

    我想通了。它在 html 标签中。

    代替:

    <script>src="quotes.js"</script>
    <script>src="script.js"</script>

    必须是:

    <script src="quotes.js"></script>
    <script src="script.js"></script>

    解决了!

    【讨论】:

      猜你喜欢
      • 2013-02-17
      • 1970-01-01
      • 2011-05-21
      • 2014-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-19
      相关资源
      最近更新 更多