js随机设置8位密码
js随机设置8位密码
设置8位密码,要求首位为大写字母,2到4位为小写字母,后四位为数字
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>demo</title>
<meta name="description" content="">
<meta name="keywords" content="">
<link href="" rel="stylesheet">
</head>
<body>
<button onclick='GetRandomNumber()'>获取</button>
<script type="text/javascript">
//首字母大写
function FirstToUpperCase(str){
var str=str.slice(0,1).toUpperCase()+str.slice(1,str.length).toLowerCase();
return str;
};
//获取密码
var number=[1,2,3,4,5,6,7,8,9,0];
var letter=['a','b','c','d','e','f','g','h','j','k']
function GetRandomNumber (){
for(var k=0; k<3; k++){
var result='';
var letterSum='';
var numberSum='';
for(var i=0; i<4; i++){
var count=parseInt(Math.random()*10);
letterSum+=letter[count];
numberSum+=number[count];
result=FirstToUpperCase(letterSum)+numberSum
}
document.write(result+'</br>');
}
}
</script>
</body>
</html>
方法二(今天看正则的时候突然想起来,就写了一种方法)
var result = [];
function getRanLetter(){
result = [];
for(var i=0;i<4;i++){
var ranNum = Math.ceil(Math.random() * 25); //生成一个0到25的数字
//大写字母'A'的ASCII是65,A~Z的ASCII码就是65 + 0~25;然后调用String.fromCharCode()传入ASCII值返回相应的字符并push进数组里
result.push(String.fromCharCode(65+ranNum));
}
var endresult=result[0]+(result[1]+result[2]+result[3]).toLowerCase()
return endresult
}
function getRanNum(){
var ranNum = (Math.ceil(Math.random() * 100000000000)).toString();;
var result=ranNum.slice(-4)
return result;
}
console.log(getRanLetter()+getRanNum())