以下代码通过在其字符的ASCII值中添加4来转换编码消息,例如:A - > D,M - > p,代码区分大小写。
var convertCode = function (sample) {
var newArray = sample.split(""); //converting string to array//
var x = newArray.length;
var testArray = [];
var resultArray = [];
for (var i = 0; i < x; i++) {
testArray.push(newArray[i].charCodeAt(0)); //conversion of characters to ASCII values//
testArray[i] = testArray[i] + 4; //ADD 4 to ASCII values
if (testArray[i] > 90 && testArray[i] <= 94) { //condition to keep uppercase alphabets within range//
testArray[i] = testArray[i] - 90 + 65;
} else if (testArray[i] > 122 && testArray[i] <= 126) { //condition to keep lowercase alphabets within range//
testArray[i] = testArray[i] - 122 + 97;
}
resultArray.push(string.fromCharCode(testArray[i]));
//converting the new Ascii values back to string//
}
resultArray.join(); //conversion of array back to string//
alert(resultArray);
};
convertCode("ABCDE");
答案 0 :(得分:3)
在您的代码中,您使用了被视为变量的string
,在运行程序时,您将获得string is not defined
,实际上您正在寻找&#39; String&#39;类而不是变量。
resultArray.push(String.fromCharCode(testArray[i]));
而不是
resultArray.push(string.fromCharCode(testArray[i]));
另外,添加3
代替4
将A
转为D
testArray[i] = testArray[i] + 4;