如何在Javascript中创建随机字符串?

时间:2017-05-11 13:59:57

标签: javascript

我想创建random个字符串。但我没有得到正确的方法。任何人都可以帮助我吗?

我的尝试:

var anysize = 3;//the size of string 
var charset = "abcdefghijklmnopqrstuvwxyz"; //from where to create
console.log( Math.random( charset ) * anysize ); //getting bad result

有可能纠正我吗?或任何其他优雅的方法来解决这个问题?

提前致谢。

3 个答案:

答案 0 :(得分:3)

function randomString(anysize, charset) {
    var res = '';
    while (anysize--) res += charset[Math.random() * charset.length | 0];
    return res;
}

像这样的东西

答案 1 :(得分:2)

您可以获取字符串charset的n-index字符,并根据需要多次附加到新字符串,请参阅以下内容:

var anysize = 3;//the size of string 
var charset = "abcdefghijklmnopqrstuvwxyz"; //from where to create
var i=0, ret='';
while(i++<anysize)
  ret += charset.charAt(Math.random() * charset.length)
  
console.log(ret);

答案 2 :(得分:1)

您要做的第一件事是创建一个可以从数组中获取随机值的辅助函数。

getRandomValue(array) {
   const min = 0; // an integer
   const max = array.length; // guaranteed to be an integer

   /*
    Math.random() will return a random number [0, 1) Notice here that it does not include 1 itself
    So basically it is from 0 to .9999999999999999

    We multiply this random number by the difference between max and min (max - min). Here our min is always 0.
    so now we are basically getting a value from 0 to just less than array.length
    BUT we then call Math.floor on this function which returns the given number rounded down to the nearest integer
    So Math.floor(Math.random() * (max - min)) returns 0 to array.length - 1
    This gives us a random index in the array
   */
   const randomIndex = Math.floor(Math.random() * (max - min)) + min;

   // then we grab the item that is located at that random index and return it
   return array[randomIndex];
}

您可以使用此辅助函数而不考虑更改字符串的长度,如下所示:

var randomString = getRandomValue(charset) + getRandomValue(charset) + getRandomValue(charset);

但是,您可能希望根据您希望随机字符串的长度创建另一个包含循环的函数:

function getRandomString(charset, length) {
  var result = '';
  for (var i = 0; i <= length; i++) {
    result += getRandomValue(charset);
  }
  return result;
}

该功能将像这样使用

var randomString = getRandomString(charset, 3);