gpt4 book ai didi

Javascript - 从一组指定值生成指定长度的随机数

转载 作者:行者123 更新时间:2023-11-30 07:06:40 29 4
gpt4 key购买 nike

我想从一组指定的字符中生成一个长度为 32 个字符的随机数。

例如:

var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZ";
var string_length = 32;

然后将使用指定的字符返回长度为 32 的随机数。

最佳答案

是这样的吗?

查看 jsfiddle。我对其进行了修改,以便您可以看到结果增长时的进展:http://jsfiddle.net/YuyNL/

var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZ";   // Pool of potential characters
var string_length = 32; // Desired length of result
var num_chars = chars.length; // Total number of characters in pool
var result = ''; // Container to store result

while(string_length--) { // Run a loop for a duration equal to the length of the result

// For each iteration, get a random number from 0 to the size of the
// number of characters you're using, use that number to grab the index
// of the character stored in 'chars', and add it to the end of the result

result += chars[ Math.floor( Math.random() * num_chars ) ];

}

$('body').append(result + '<br>'); // This just appends the result to the 'body'
// if you're using jQuery

关于Javascript - 从一组指定值生成指定长度的随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2834244/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com