我正在用 Javascript 做一个随机生成器。
什么不起作用?
我经常(大约 80% 的时间)将 undefined
值作为此脚本中的第一个值。如果我使数组更大,错误发生的频率就会降低。
什么时候生效?
如果我用相同数量的条目创建两个数组,我不会收到错误。
如果我将 * two.length);
与 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);
}
关于javascript - 我多次从随机数组中得到 undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50037237/