我想创建random
字符串。但我没有找到正确的方法。有人可以帮助我吗?
我的尝试:
var anysize = 3;//the size of string
var charset = "abcdefghijklmnopqrstuvwxyz"; //from where to create
console.log( Math.random( charset ) * anysize ); //getting bad result
可以纠正我吗?或者任何其他优雅的方法来解决这个问题?
提前致谢。
最佳答案
您应该使用可能的字符字符串(字符集)的.length
属性。
此外,使用 Math.floor
方法来获取 chars
数组的integer
位置。
您可以使用其数组index
从charset
字符串中获取随机项:
charset[Math.floor(Math.random() * charset.length)]
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);
关于javascript - 如何在 JavaScript 中创建随机字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43917622/