我需要用字母A和数字5-9生成~6个随机字符.这能用Math.random来完成吗?它们不一定每次都是独一无二的。我发现了这个:
Math.floor(0|Math.random()*9e6).toString(36)
而且它确实工作得很好,但我可以修改它,使它使用某些字符(类似于replace(/[^a-z]+/g, ''),但以更具体的方式)而不添加arrays等等?
编辑:第五个人的答案在哪里?
发布于 2018-02-03 16:06:08
您可以在想要的范围内使用不同的函数,对字母和数字使用不同的因素和偏移。
function getRandomLetter() { // A B C D E F G
return Math.floor(Math.random() * 7 + 10).toString(36).toUpperCase();
// ^ count of wanted letters
// ^^ offset for the first letter, to get A
// with a random result of zero
}
function getRandomNumber() { // 5 6 7 8 9
return Math.floor(Math.random() * 5 + 5).toString(36);
// ^ 9 - 5 + 1 or count, as factor
// ^ offset
}
console.log(getRandomLetter());
console.log(getRandomNumber());
发布于 2018-02-03 16:07:55
完全可以使用数学从数组中选择随机元素(在本例中是构建随机Id代码的字符),并将这些字符连接到代码字符串中。
步骤:
代码:
const array = ["A", "B", "C", "D", "E", "F", "G", "5", "6", "7", "8", "9"];
let codeString = "";
for(i=0 ; i<6 ; i++){
const randomIndex = Math.floor(Math.random()* array.length);
codeString = codeString + array[randomIndex];
}
console.log(codeString);发布于 2018-02-03 16:16:08
如果随机字符出现的模式不是很重要,那么我会这样做
// This function helps us generate a random number between two numbers.
function random(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// The characters we need
var characterArray = ["A", "B", "C", "D", "E", "F", "G", 1, 2, 3, 4, 5, 6, 7, 8, 9];
// Now run a loop six times, get a random number between 0 and the length of the characterArray and concatenate it into a new variable
var randomString = "";
for ( var i = 0; i < 6; i++) {
randomString += characterArray[ random(0, characterArray.length - 1) ];
}
console.log( randomString );代码可以进一步缩短,例如,与实际创建一个字符数组不同,我们可以将字符串characterArray = "ABCDE...7,8,9"赋值为字符串,它也是一个字符数组,并具有类似的用途,但我认为,以一种不言自明的方式编写它将是一个好主意,以便您理解、添加或更改代码中的任何内容。
通过一个函数在两个数字之间给出一个随机数,我们可以使用一个数组,该数组包含我们的结果可能具有的所有字符。然后,由于我们想要得到一个包含6个不同字符的随机数,我们使用一个for loop,运行它六次,每次它从字符数组中得到一个随机元素,并完成这项工作。
https://stackoverflow.com/questions/48599218
复制相似问题