我在Javascript中做一个随机生成器。
什么不起作用?
我经常得到undefined
值(大约80%的时间)作为此脚本中的第一个值。如果我将数组放大,则错误发生的次数会减少。
什么时候有用?
如果我使两个数组的条目数相同,我就不会收到错误。
如果我将* 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();
答案 0 :(得分:2)
您需要为随机索引使用不同的变量。
将第二个较长的数组作为获取随机索引的最终值。这适用于第二个数组,但不适用于第一个数组。
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);
}
答案 1 :(得分:2)
您要覆盖第一个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];
}
答案 2 :(得分:1)
您可以创建一个可重复使用的函数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>