【发布时间】: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”已被声明。
我不明白为什么会出现此错误。我做错了什么?
【问题讨论】:
-
请修正您问题的格式 -> How do I format my posts using Markdown or HTML?
-
你不能用
const重新声明一些东西。如果您在控制台中复制和粘贴,则不需要const声明。 -
您在控制台中执行的任何操作都发生在全局范围内。如果你再次执行相同的脚本,变量已经被声明了——除非你之前已经“重置”了那个(全局)范围——>A way to reset Chrome DevTools console's context