How to create random string in Javascript?
本问题已经有最佳答案,请猛点这里访问。
我想创建
我的尝试:
1 2 3 | var anysize = 3;//the size of string var charset ="abcdefghijklmnopqrstuvwxyz"; //from where to create console.log( Math.random( charset ) * anysize ); //getting bad result |
可以纠正我吗?或者其他优雅的方法来解决这个问题?
事先谢谢。
1 2 3 4 5 | function randomString(anysize, charset) { var res = ''; while (anysize--) res += charset[Math.random() * charset.length | 0]; return res; } |
像那样的
您应该使用您的字符串(字符集)的
另外,使用
您可以使用其数组
1 | charset[Math.floor(Math.random() * charset.length)] |
1 2 3 4 5 6 | var anysize = 3;//the size of string var charset ="abcdefghijklmnopqrstuvwxyz"; //from where to create result=""; for( var i=0; i < anysize; i++ ) result += charset[Math.floor(Math.random() * charset.length)]; console.log(result); |
您可以获取字符串
1 2 3 4 5 6 7 | 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); |
您要做的第一件事是创建一个助手函数,该函数可以从数组中获取随机值。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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]; } |
您可以使用这个助手函数而不考虑更改字符串的长度,如下所示:
1 | var randomString = getRandomValue(charset) + getRandomValue(charset) + getRandomValue(charset); |
但是,您可能希望创建另一个函数,该函数包含一个基于您希望随机字符串的长度的循环:
1 2 3 4 5 6 7 | function getRandomString(charset, length) { var result = ''; for (var i = 0; i <= length; i++) { result += getRandomValue(charset); } return result; } |
这个函数的用法是这样的