Uncaught SyntaxError: Identifier 'x' has already been declared

Uncaught SyntaxError: Identifier 'x' has already been declared

我是 JavaScript 和网络开发的新手,目前正在使用 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))]);

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

未捕获语法错误:标识符 'quoteMessage' 已声明。

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

既然你说你是直接粘贴到控制台,你不能重新声明一个 const 变量。

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

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