JS入门开发者编写随机名言生成器出现数组元素为undefined问题求助
问题根因
计算随机索引的代码行中,数组长度属性名拼写错误,将正确的length错写为lenth,缺失了字母g。
由于不存在quotes.lenth属性,读取该属性会得到undefined,代入随机数运算后得到NaN,用非法下标访问数组最终返回undefined。
修复方法
仅需修改点击事件监听内的属性拼写即可,修改后的完整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.length)]; output.innerHTML = randomQuote; });
调试建议
后续遇到同类运行异常可以优先打开浏览器开发者工具的控制台面板,属性拼写、语法类错误都会有明确的报错提示,能大幅提升排查效率。
内容的提问来源于stack exchange,提问作者TomDev
相关产品推荐
相关产品推荐

