javascript - 数组中的随机元素未定义
问题描述
我已经完成了作为初学者 JS 编码器的工作,并通过单击按钮从数组中重新设计了报价生成器应用程序。每次按下按钮时,我都设法显示下一个元素。但是,在本教程中,元素是随机显示的,所以我按照说明进行操作,但我得到的不是随机引用,而是“未定义”。我被困住了。在我看来,我所做的一切都是正确的,但我可能在某个地方滑倒了。谁能帮我?
let btn = document.getElementById("btn");
let output = document.getElementById("output");
let quotes = [
"The greatest glory in living lies not in never falling, but in rising every time we fall. -Nelson Mandela",
"The way to get started is to quit talking and begin doing. -Walt Disney",
"Your time is limited, so don't waste it living someone else's life. Don't be trapped by dogma – which is living with the results of other people's thinking. -Steve Jobs",
"If life were predictable it would cease to be life, and be without flavor. -Eleanor Roosevelt",
"If you look at what you have in life, you'll always have more. If you look at what you don't have in life, you'll never have enough. -Oprah Winfrey",
"If you set your goals ridiculously high and it's a failure, you will fail above everyone else's success. -James Cameron",
"Life is what happens when you're busy making other plans. -John Lennon",
];
btn.addEventListener("click", function() {
let randomQuote = quotes[Math.floor(Math.random() * quotes.lenth)];
output.innerHTML = randomQuote;
});
<h1>Quote Generator</h1>
<div class="content">
<button id="btn">Press for a new Quote!</button>
<p id="output">Press the button to generate a quote.</p>
</div>
解决方案
您的代码完美quotes.lenth
--> quotes.length
:)
推荐阅读
- javascript - TypeError:无法分配给只读属性
- mysql - MySQL 从一个表返回结果取决于另一个表(主类别)中是否存在数据
- typescript - TypeScript - 防止 null 的类型保护
- python-3.x - 从只有唯一值的熊猫数据框中创建 python 字典
- java - Euler Project #5 Java- if 语句不执行
- google-apps-script - 终止 Google Dashboard 中所有正在运行的脚本
- javascript - 无法在firestore中获得第三个子集合反应本机
- c# - 将复杂对象返回到视图
- mysql - Grafana 不读取日期时间列
- twitter - 当我已经在 Twitter 网络视图中时,如何让 https://twitter.com/intent/tweet?text= 正常工作而不让我再次登录