javascript - 未捕获的类型错误:quotesData[currentQuote] 未定义
问题描述
我尝试构建一个简单的 javasciprt 随机报价应用程序,但在我的代码的第一次测试中,我在控制台中看到了这个: Uncaught TypeError: quotesData[currentQuote] is undefined showquote http://127.0.0.1:5500/js/main.js :31 http://127.0.0.1:5500/js/main.js:37
这是js代码源:
quotesData = [{
quote: `There are only two ways to live your life. One is as though nothing is a miracle. The other is as though everything is a miracle.`,
name: 'Albert Einstein '
},
{
quote: `Good friends, good books, and a sleepy conscience: this is the ideal life.`,
name: 'Mark Twain'
},
{
quote: `Life is what happens to us while we are making other plans.`,
name: 'Allen Saunders '
},
{
quote: `It's not the load that breaks you down, it's the way you carry it.`,
name: 'Lou Holt'
},
{
quote: `Try not to become a man of success. Rather become a man of value.`,
name: 'Albert Einstein '
},
]
/* important variables */
const currentQuote = quotesData[0];
const quoteText = document.getElementById('quote');
const quotebtn = document.getElementById('q-btn');
const quotepan = document.getElementById('q-span');
/* this function is for show the quote and author name */
function showquote() {
quoteText.innerText = quotesData[currentQuote].quote;
quotespan.innerText = quotesData[currentQuote].name;
currentQuote++;
};
/* this function is for change the quote and author name with evrey click */
quotebtn.addEventListener('click', showquote())
解决方案
currentQuote
不是数组索引,它是数组的一个元素。
您需要将其设置为,如果您想增加它,则0
不能。const
let currentQuote = 0;
此外, to 的第二个参数addEventListener
应该是对函数的引用。您立即调用该函数,而不是将其保存为侦听器。
quotebtn.addEventListener('click', showquote);
在你 increment 之后currentQuote
,你需要检查你是否已经到达数组的末尾并环绕。您可以使用模数运算符来执行此操作。
function showquote() {
quoteText.innerText = quotesData[currentQuote].quote;
quotespan.innerText = quotesData[currentQuote].name;
currentQuote = (currentQuote + 1) % quotesData.length;
};
推荐阅读
- python - 如何为 32 位系统构建我的 react 前端和 django 后端应用程序?
- c# - 如何在 Unity 中进行网络连接?
- android - 无法在带有颤振应用程序的手机上运行或调试
- c# - 使用 C# 和 Exchange 2019 在员工的 Outlook 日历中创建约会
- python - Pandas 按小时重新采样数据会创建不存在的数据
- xml - 雪花:无法递归解析 xml
- excel - 类型不匹配问题 VBA - 公式到值
- python - 如何使用命令行在 Windows 上使用 openvpn?
- rust - 函数参数名称前的“mut”是什么意思?
- scala - 如何使用 JWT Authenticator 访问 Play Silhouette 中受保护的资产