繁体   English   中英

我从随机数组中多次未定义

[英]I get undefined many times from random array

我在Javascript中做一个随机生成器。

什么不起作用?

我经常得到undefined值(大约80%的时间)作为此脚本中的第一个值。 如果我将数组放大,则错误发生的次数会减少。

什么时候会起作用?

如果我使两个数组具有相同数量的条目,我不会得到错误。

如果我在* two.length);的代码中交换顺序* two.length); with one.length); 它也有效。

你能发现错误吗? 它让我疯狂,非常奇怪。

var one = ['Abashed',
           'Abhorrent',
           'Party',
           'Zing',
           'Zip',
           'Zippy'];

var two = ['Account', 
           'Wives', 
           'Wills', 
           'Wins',
           'Wounds',
           'Wrecks',
           'Wrists',
           'Writings',
           'Wrongs',
           'Years',
           'Yellows',
           'Young',
           'Youths',
           'Zings',
           'Zips'];

function showrandom() {
  var rand = Math.floor(Math.random() * one.length);
  var rand = Math.floor(Math.random() * two.length);

  document.getElementById('random').innerHTML = one[rand] + ' ' + two[rand];
}

showrandom();

您需要为随机索引使用不同的变量。

您将第二个较长的数组作为获取随机索引的最终值。 这适用于第二个数组,但不适用于第一个数组。

function showrandom() {
    var rand1 = Math.floor(Math.random() * one.length),
        rand2 = Math.floor(Math.random() * two.length);

    document.getElementById('random').innerHTML = one[rand1] + ' ' + two[rand2];
}

要解决此问题,您可以使用函数通过移交数组来获取随机值。

function getRandomItem(array) {
    return array[Math.floor(Math.random() * array.length)];
}

function showrandom() {
    document.getElementById('random').innerHTML =
        getRandomItem(one) + ' ' + getRandomItem(two);
}

您将覆盖第一个rand变量,因为两个随机值都分配给相同的变量名称。 这将导致undefined因为第一个数组比第二个更短。 这是一个简单的解决方案。 只需重命名其中一个变量即可。

function showrandom() {
  var rand1 = Math.floor(Math.random() * one.length);
  var rand2 = Math.floor(Math.random() * two.length);


  document.getElementById('random').innerHTML = one[rand1] + ' ' + two[rand2];
}

您可以创建一个可重用的函数getRandom(randomArray) ,可以调用该函数来获取随机数。

 var one = ['Abashed', 'Abhorrent', 'Party', 'Zing', 'Zip', 'Zippy']; var two = ['Account', 'Wives', 'Wills', 'Wins', 'Wounds', 'Wrecks', 'Wrists', 'Writings', 'Wrongs', 'Years', 'Yellows', 'Young', 'Youths', 'Zings', 'Zips']; function getRandom(randArray){ return Math.floor(Math.random() * randArray.length); } function showrandom() { document.getElementById('random').innerHTML = one[getRandom(one)] + ' ' + two[getRandom(two)]; } showrandom(); 
 <div id='random'></div> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM