【问题标题】:I dont know why this random quote generator shows undefined most often我不知道为什么这个随机报价生成器最常显示未定义
【发布时间】:2017-11-06 22:04:44
【问题描述】:

为什么下面的代码大部分时间都显示undefined

var fragOne = ["From morning until night", "Most pastors in church", "Hollywood movies in the 21st century", "Never disrespect anyone unless"];

var fragTwo = ["start after the weekend", "the Christians nowadays", "my friend Jacob in Class", "because of snowfall during winter"];

var fragThree = ["some girls in the class.", "intelligent Pilots in the UK.", "Several girls in my complex.", "If I believe in God."];

var button = document.getElementById("btn");

button.addEventListener("click", function(){
    var displaying = document.getElementById("display");

    var randomOne = Math.floor(Math.random()*fragOne.length);
    var randomTwo = Math.floor(Math.random()*fragTwo.length);
    var randomThree = Math.floor(Math.random()*fragThree.length);
    var combineRandom = randomOne+randomTwo+randomThree;

    display.innerHTML = fragOne[combineRandom]+" "+fragTwo[combineRandom]+" "+fragThree[combineRandom];
    console.log(fragOne[combineRandom]+" "+fragTwo[combineRandom]+" "+fragThree[combineRandom]);

});

【问题讨论】:

  • 调试你的代码,你就会明白为什么。提示:您不想通过 combineRandom 进行索引,而是要组合字符串 combineRandom = fragOne[randomOne] + fragTwo[randomTwo] + fragThree[randomThree]

标签: javascript quotes


【解决方案1】:

基本上你需要取随机索引并从数组中获取值。

var combineRandom = fragOne[randomOne] + " " + fragTwo[randomTwo] + " " + fragThree[randomThree];

display.innerHTML = combineRandom;
console.log(combineRandom);

正如它所写的那样,您添加所有随机索引并将其用于任何数组以获取元素。获得undefined 的原因是,您的索引可能大于数组中的项目。获取undefined 是数组或对象和未定义属性的常见行为。

【讨论】:

    【解决方案2】:

    您将三个数字 randomOnerandomTworandomThree 相加,它们都可以取 0 到 1 之间的值(Math.random 返回一个介于 0 和 1 之间的值并乘以数组长度,即 4)。因此,如果您处理索引处的元素是这三个元素的总和,那么您很容易超过数组的长度,因此您得到undefined

    【讨论】:

      【解决方案3】:

      您在代码中犯了一个错误,您不需要将随机数相加,只需使用每个来获取随机引用,请参见下文:

      不需要此代码:

       var combineRandom = randomOne+randomTwo+randomThree;
      

      只需这样做并适应您的 html 渲染

       console.log(fragOne[randomOne]+" "+fragTwo[randomTwo]+" "+fragThree[randomTh`ree]);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-17
        • 2011-05-21
        • 1970-01-01
        • 2021-03-31
        • 2021-05-15
        • 2021-04-06
        相关资源
        最近更新 更多