首页 > 解决方案 > 未捕获的类型错误: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())    

标签: javascript

解决方案


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;
};

推荐阅读