First of all, I will introduce to you how js generates 26 uppercase and lowercase letters, mainly using the str.charCodeAt() and String.fromCharCode() methods
1. Use charCodeAt() to obtain the Unicode encoding of a specific character in the string.
2. fromCharCode() can accept one (or more) specified Unicode values and then return the corresponding string.
//生成大写字母 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<str.length;i++){ codes.push(str.charCodeAt(i)); } return codes; } function generateSmall(){ var ch_small = 'a'; var str_small = ''; for(var i=0;i<26;i++){ str_small += String.fromCharCode(ch_small.charCodeAt(0)+i); } return str_small; } function generateBig(){ var ch_big = 'A'; var str_big = ''; for(var i=0;i<26;i++){ str_big += String.fromCharCode(ch_big.charCodeAt(0)+i); } return str_big; } console.log(generateBig()); console.log(generateSmall()); console.log(toUnicode(generateBig())); console.log(toUnicode(generateSmall())); console.log(generateBig_1()); console.log(generateSmall_1());
The following introduces js to randomly generate 26 uppercase and lowercase letters, the key line of code:
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());
The above code achieves our requirements and can randomly output uppercase letters or small letters. The principle is very simple, which is achieved by using the interval of Unicode codes of uppercase letters or lowercase letters.
Code 2:
/** * 返回一个随机的小写字母 */ 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; }
This article mainly introduces how to use javascript to output random uppercase letters or lowercase letters. I hope it can bring you more or less help.