大家晚上好,
我正在尝试生成一个包含8个字符的字符串,这些字符是从数组中随机选择的。这就是我正在使用的:
var myArrayPismo = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
while(myArrayPismo.length < 9){
var randomletter = Math.ceil(Math.random()*myArrayPismo.length)
if(myArrayPismo.indexOf(randomletter) > -1) continue;
myArrayPismo[myArrayPismo.length] = randomletter;
}
由于某种原因,它只打印出所有字母。
这是我的号码生成功能:
var kodCisla = [];
while(kodCisla.length < 9){
var randomnumber = Math.ceil(Math.random()*9)
if(kodCisla.indexOf(randomnumber) > -1) continue;
kodCisla[kodCisla.length] = randomnumber;
}
哪个工作正常。除了我希望它能够生成2个或更多相同的数字,而不是每次都不同。
我的目标是随机获得一系列字母:KODlkSmQW
以及一串随机数字,也可以像这样重复:887562327
任何有关这些问题的帮助都将不胜感激。
答案 0 :(得分:1)
可以从数组中提取随机元素的函数在这里很有用。注意使用Math.floor
而不是Math.ceil
,以及返回语句之前的数组访问。
function randomElement (array) {
return array[Math.floor(Math.random() * array.length)]
}
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split(''),
result = '';
for (var i = 0; i < 8; i++) {
result += randomElement(characters)
}
console.log(result) //=> (random 8-character string)
&#13;
对于随机数,您可以使用类似的randomInRange
函数:
function randomInRange (a, b) {
a |= 0
b |= 0
return Math.floor(Math.random() * (b - a + 1)) + a
}
var result = []
for (var i = 0; i < 8; i++) {
result.push(randomInRange(0, 9))
}
console.log(result) //=> (eight random digits)
&#13;
答案 1 :(得分:0)
你的第一个while
循环永远不会运行,因为它基于myArrayPismo.length < 9
的条件,因为你只是将它设置为包含所有26个字母,所以它已经是假的。所以,当你稍后再去看它时,你会得到所有的原始值。你需要的是一个额外的数组,用于生成生成的random。
此外,在这种情况下远离while
循环,因为您确切知道要循环的次数,因此请改用常规for
循环。
你的第二个数组(带数字)可以做到这一点,当然可以连续两次提出相同的随机数。
但是,在将随机数推入数组之前,两个数组都不需要执行任何操作。
最后,正如我所提到的,不要使用Math.ceil
,因为您永远不会将第一个元素作为随机元素返回,而是使用Math.floor
。
var myArrayPismo = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
var resultArray = [];
for(var i = 0; i < 8; ++i){
resultArray.push(myArrayPismo[Math.floor(Math.random()*myArrayPismo.length)]);
}
console.log(resultArray.join(""));