1. 方法
- 字符 → ASCII 码:
StringValue.charCodeAt()
- ASCII 码 → 字符:
String.fromCharCode(asciiValue)
2. 打印 26 个字母的 ASCII 码
var charToASCII = function() {
var charList = "";
for (var i = "a".charCodeAt(); i <= "z".charCodeAt(); i++) {
charList = charList + String.fromCharCode(i) + " —— " + i + "\n";
}
for (var i = "A".charCodeAt(); i <= "Z".charCodeAt(); i++) {
charList = charList + String.fromCharCode(i) + " —— " + i + "\n";
}
console.log(charList);
return charList;
}
charToASCII();
3. 凯撒加密
由于 JavaScript 是弱类型语言,字母和字母可以做加减运算,所以 JavaScript 中的字符计算就要经过 ASCII 码的转换。
var nextCharacter = function(asciiValue, k) {
var s = asciiValue;
// 获取给定字母的后面第 k 个字母
if ((s >= 65 && s <= 90) || (s >= 97 && s <= 122)) {
if ((s + k >= 65 && s + k <= 90) || (s + k >= 97 && s + k <= 122)) {
return String.fromCharCode(s + k);
} else {
return String.fromCharCode(s + k - 26);
}
}
// 非字母字符不变化
else {
return String.fromCharCode(s);
}
}
var caesarCipher = function(stringValue, k) { // k 表示每个字母向右移动 k 位
var newString = "";
for (var i = 0; i < stringValue.length; i++) {
newString += nextCharacter(stringValue[i].charCodeAt(), k);
}
return newString;
}
console.log(`Old String: "HelloWord! ^-^", Encrypted String: "${caesarCipher("HelloWord! ^-^", 3)}"`);
输出结果:Old String: "HelloWord! ^-^", Encrypted String: "KhoorZrug! ^-^"
这里有个大牛的版本,用了更多 JavaScript 的特性:凯撒加密解密的 JavaScript 版本