首先为大家介绍js生成26个大小写字母,主要用到 str.charCodeAt()和 String.fromCharCode()方法
1、使用 charCodeAt()来获得字符串中某个具体字符的 Unicode 编码。
2、fromCharCode()可接受一个(或多个)指定的 Unicode 值,然后返回对应的字符串。
//生成大写字母 A的Unicode值为65
function generateBig_1(){
var str = [];
for(var i=65;i<91;i++){
str.push(String.fromCharCode(i));
}
return str;
}
//生成大写字母 a的Unicode值为97
function generateSmall_1(){
var str = [];
for(var i=97;i<123;i++){
str.push(String.fromCharCode(i));
}
return str;
}
//将字符串转换成Unicode码
function toUnicode(str){
var codes = [];
for(var i=0;i
下面为大家介绍js随机生成26个大小写字母,关键行代码:
function getCharacter(flag){
var character="";
if(flag==="lower"){
character = String.fromCharCode(Math.floor(Math.random()*26)+"a".charCodeAt(0));
}
if(flag==="upper"){
character = String.fromCharCode(Math.floor(Math.random()*26)+"A".charCodeAt(0));
}
return character;
}
function getUpperCharacter(){
return getCharacter("upper");;
}
function getLowerCharacter(){
return getCharacter("lower");;
}
console.log(getUpperCharacter());
console.log(getLowerCharacter());
以上代码实现了我们的要求,能够随机输出大写字母或者些小字母,原理非常的简单,就是利用了大写字母或者小写字母Unicode码的区间来实现的。
代码二:
function getLowerCharacter(){
return getCharacter("lower");;
}
function getUpperCharacter(){
return getCharacter("upper");;
}
function getCharacter(flag){
var character = "";
if(flag === "lower"){
character = String.fromCharCode(Math.floor( Math.random() * 26) + "a".charCodeAt(0));
}
if(flag === "upper"){
character = String.fromCharCode(Math.floor( Math.random() * 26) + "A".charCodeAt(0));
}
return character;
}
本文主要介绍了如何使用javascript实现输出随机的大写字母或者小写字母,希望能够给大家带来或多或少的帮助。



