这是我目前所拥有的,但它只打印加密中的第一个字母。我哪里错了?
function crypto(){
var password = "Pizza2Day";
var flag = 0;
var encryptedPassword= "";
var originalValues = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];
var encryptedValues = ["m", "h","t","f","g","k","b","p","j","w","e","r","q","s","l","n","i","u","o","x","z","y","v","d","c","a"];
for (var i=0; i < password.length; i++){
flag=0;
for (var r = 0; r < originalValues.length; r++){
if (originalValues[r] == password.charAt(i)){
encryptedPassword = encryptedPassword + encryptedValues[r];
flag = 1;
break;
} else if (originalValues[r].toUpperCase() == password.charAt(i)) {
encryptedPassword = encryptedPassword +
encryptedValues[r].toUpperCase();
flag = 1;
break;
}
}
if (flag == 0) {
encryptedPassword = encryptedPassword + password.charAt(i);
}
return encryptedPassword;
}
}
console.log("New Password: " + crypto());
答案 0 :(得分:0)
您需要将return
语句放在for
循环之外:
function crypto() {
var password = "Pizza2Day";
var flag = 0;
var encryptedPassword = "";
var originalValues = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];
var encryptedValues = ["m", "h", "t", "f", "g", "k", "b", "p", "j", "w", "e", "r", "q", "s", "l", "n", "i", "u", "o", "x", "z", "y", "v", "d", "c", "a"];
for (var i = 0; i < password.length; i++) {
flag = 0;
for (var r = 0; r < originalValues.length; r++) {
if (originalValues[r] == password.charAt(i)) {
encryptedPassword = encryptedPassword + encryptedValues[r];
flag = 1;
break;
} else if (originalValues[r].toUpperCase() == password.charAt(i)) {
encryptedPassword = encryptedPassword +
encryptedValues[r].toUpperCase();
flag = 1;
break;
}
}
if (flag == 0) {
encryptedPassword = encryptedPassword + password.charAt(i);
}
}
return encryptedPassword;
}
console.log("New Password: " + crypto());
&#13;
答案 1 :(得分:0)
你可以通过使用字符串代替数组来获取另一个方法,并使用String#indexOf
来获取给定字符串的索引。
检查索引是否为-1
,字符串中缺少字符的值不是必需的,因为此值被视为加密字符串的索引。这会返回一个字符或undefined
,即falsy。结合以下logical OR ||
,将获取下一个值,在本例中为要编码的字符串的原始字符。
检查原始字符是否为大写字符后,该字符将转换为大写,然后添加到结果字符串中。
function crypto() {
var password = "Pizza2Day",
encryptedPassword = "",
original = "abcdefghijklmnopqrstuvwxyz",
encrypted = "mhtfgkbpjwerqslniuoxzyvdca",
i, character;
for (i = 0; i < password.length; i++) {
character = encrypted[original.indexOf(password[i].toLowerCase())] || password[i];
if (password[i] === password[i].toUpperCase()) {
character = character.toUpperCase();
}
encryptedPassword += character;
}
return encryptedPassword;
}
console.log("New Password: " + crypto());
&#13;