java版本
import java.util.Random;
public class GenerateValidCode
{
public static String getValidCode()
{
String str="0123456789";
StringBuilder sb=new StringBuilder(4);
for(int i=0;i<4;i++)
{
char ch=str.charAt(new Random().nextInt(str.length()));
sb.append(ch);
}
return sb.toString();
}
}
js版本
var generateCode = function(source,length) {
var randomInt = function(min,max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
var retStr = '';
for(var index = 0; index < length; index++)
{
retStr += source[randomInt(0,source.length - 1)]
}
return retStr;
}
console.log(generateCode('0123456789',6));