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

时间:2010-05-14 12:52:01

标签: javascript jquery

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

例如:

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

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

5 个答案:

答案 0 :(得分:4)

这样的东西?

查看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

答案 1 :(得分:2)

var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZ";
var string_length = 32;
var myrnd = [], pos;

// loop as long as string_length is > 0
while (string_length--) {
    // get a random number between 0 and chars.length - see e.g. http://www.shawnolson.net/a/789/make-javascript-mathrandom-useful.html
    pos = Math.floor(Math.random() * chars.length);
    // add the character from the base string to the array
    myrnd.push(chars.substr(pos, 1));
}

// join the array using '' as the separator, which gives us back a string
myrnd.join(''); // e.g "6DMIG9SP1KDEFB4JK5KWMNSI3UMQSSNT"

答案 2 :(得分:2)

// Set up a return variable
var randStr = "";

// Split the chars into individual array elements
chars = chars.split("");

// Until string_length is 0...
while (string_length--)
    // ... select a random character from the array
    randStr += chars[Math.floor(Math.random() * chars.length)];

// return the string
return randStr;

答案 3 :(得分:2)

这是一个非常容易理解的简单解决方案。

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

for(var i=0; i<string_length; i++){
  var randomPos = Math.floor( Math.random() * chars.length );
  result += chars.substr(randomPos, 1);
}

答案 4 :(得分:1)

也许让它变得更灵活。

您可能希望返回数组, 如果你打算做任何大整数数学

function charsRandom(len, chars){
    chars= chars || "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    len= len || 32;
    var cr= [], L= chars.length;
    while(len--) cr[cr.length]= chars.charAt(Math.floor(Math.random()*L));
    return cr.join(''); // or return the array cr
}

警报(charsRandom())