Javascript 未捕获类型错误:quotesData[currentQuote]未定义
我试图构建一个简单的javasciprt随机报价应用程序,但在我的代码的第一次测试中,我在控制台中看到了这一点:uncaughtTypeError:quotesData[currentQuote]未定义 秀辞 http://127.0.0.1:5500/js/main.js:37 这是js源代码:Javascript 未捕获类型错误:quotesData[currentQuote]未定义,javascript,Javascript,我试图构建一个简单的javasciprt随机报价应用程序,但在我的代码的第一次测试中,我在控制台中看到了这一点:uncaughtTypeError:quotesData[currentQuote]未定义 秀辞 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
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;
另外,addEventListener
的第二个参数应该是对函数的引用。您正在立即调用该函数,而不是将其保存为侦听器
quotebtn.addEventListener('click', showquote);
在递增currentQuote
后,需要检查是否已到达数组末尾并环绕。可以使用“模数”操作符执行此操作
function showquote() {
quoteText.innerText = quotesData[currentQuote].quote;
quotespan.innerText = quotesData[currentQuote].name;
currentQuote = (currentQuote + 1) % quotesData.length;
};
您的代码有几个问题-
quotebtn.addEventListener('click',showquote())
替换为quotebtn.addEventListener('click',showquote)
,否则您将向函数传递showquote的返回值currentQuote
是一个对象,不能作为索引传递。您需要将currentQuote
设置为0
,以便可以增加它。
这仍然不是随机引用,但它解决了您的问题currentQuote
是一个常量变量-这意味着不能增加它,因为++
实际上只是+=1
的语法糖,而currentQuote=currentQuote+1
本身就是语法糖。把它改成“让”不要混合ES5和ES6。只有在需要访问
此
关键字时,才能使用旧功能。否则,出于语义目的,请坚持使用一个版本。quotebtn.addEventListener('click',showquote())
K我回答了这个问题,但我从未听说过形式的错误。。。未定义
。这更像是无法读取属性。。。未定义的属性
。您首先从哪里得到错误消息的?