【问题标题】:Uncaught SyntaxError: Identifier 'x' has already been declared未捕获的 SyntaxError:标识符“x”已被声明
【发布时间】:2021-06-25 10:06:38
【问题描述】:

我是 JavaScript 和 web 开发的新手,目前正在 Codecademy 上一门课程。我正在创建一个随机消息应用程序,其中包含一组对象并在运行时打印一条随机消息。

我创建的对象数组如下:

const quoteMessage = [
    {   title   : "It’s up to you.",
        meaning : "This one speaks for itself, really. No one is going to achieve your dream for you, and likewise, no one can stop you. It’s up to you.",
        aurthor : "Unknown.",
    },
    {   title   : "Failure is the opportunity to begin again more intelligently.",
        meaning : "For being only nine words long, this is an incredibly powerful, thought-provoking quote. It’s also incredibly accurate if you take the time to think about it. With every failure, we learn and grow, meaning that when we start over we’re almost guaranteed to do a better job. Failure isn’t a step back; it’s a step forward.",
        aurthor : "Henry Ford.",
    },
    {   title   : "The best revenge is massive success.",
        meaning : "It can be hard not to lash out at the people who tell you that you’re never going to succeed. However, if you let anger and hatred consume you, you’re never going to get anywhere and you’ll just prove them right. Rather than shout and swear, why not watch their faces as you mount that last step and reach the top?",
        aurthor : "Unknown.",
    }];

我创建了如下随机选择器:

console.log(quoteMessage[Math.floor(Math.random()*(quoteMessage.length - 1))]);

我正在将此代码直接复制并粘贴到控制台中。运行代码时出现错误:

未捕获的 SyntaxError:标识符“quoteMessage”已被声明。

我不明白为什么会出现此错误。我做错了什么?

【问题讨论】:

标签: javascript syntax-error


【解决方案1】:

由于您说是直接粘贴到控制台中,因此无法重新声明 const 变量。

要么使用letvar,要么将代码放入要重新加载的HTML 文件中的<script>

【讨论】:

  • 这是一个直接的答案。
  • “要么使用let...” - 您可能需要在将其发布为答案之前对其进行测试...
  • “Why”的解释对未来的读者和OP非常有用。
【解决方案2】:

如果您已经在代码的其他地方的同一变量中使用了此类声明,则不要在新变量代码中重复声明“let、const 或 var”。示例:让 ageJohn = 25;现在如果你想在代码中再次写ageJohn,不要写let,只需写ageJohn = 25; 我希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2021-10-25
    • 2021-09-29
    • 2018-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-26
    • 2021-03-28
    • 1970-01-01
    相关资源
    最近更新 更多