如何使数组中的元素改变它的位置



我是JS的初学者。我试图理解凯撒密码ROT13,但这对我来说太复杂了。所以我尝试编写自己的代码。下面是:

function encrip() {
var alphabet = ["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 str = "Ni Hao"; 
var string = str.toUpperCase();
for (var i = 0; i < string.length; i++) {
for (var k = 0; k < alphabet.length; k++) {
if(string.charAt(i) == alphabet[k]) {
/* console.log(string.charAt(i) + ' ' + alphabet.indexOf(alphabet[k])); */
}
}
}
}
encrip();

但我被困住了。怎么做:

1.从 var str 获取值,然后访问 var alphabet,将每个字母从 var str 值更改为字母表中的下一个 3 个(var str 每个元素的当前位置都会改变( 例如:Input: Ni Hao ==> output: QL KDR

2.创建通用代码,我的意思是,不仅要更改位置 3,而且当我给出值"5"时,每个元素都会从字母表中更改接下来的 5 个位置。所以当我改变它的值时,输出可以改变

我希望我清楚地解释了一切。提前感谢大家的帮助!!

可以使用以下函数加密英文单词,第一个参数是要加密的字符串,第二个参数是用于移位的字符串

function encryp(str,pos){
var alpha="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var strUC=str.toUpperCase();
var enc="";
for(var i=0;i<strUC.length;i++){
if(strUC.charAt(i)!=" "){
enc+=alpha.charAt((alpha.indexOf(strUC.charAt(i))+pos)%26)
}
else{
enc+=" "
}
// in your case pos=3
}

return enc;
}
console.log(encryp("NiHao",3));

  • 你不需要两个 for 循环来执行此操作。遍历输入string并查找alphabet数组中每个字符的索引,如果找到,则向其添加shift以获取加密字符。

  • 要处理溢出,请使用模运算符在数组中循环。 另外,我假设您不会使用任何特殊符号进行加密。

function encrip(string, shift) {
var alphabet = ["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"];
string = string.toUpperCase();
let arr = [];
for (var i = 0; i < string.length; i++) {
let char = alphabet.indexOf(string[i]) !== -1 ? alphabet[(alphabet.indexOf(string[i]) %26) + shift] : " ";
arr.push(char);
}
let encryp = arr.join("");
console.log(encryp);
return encryp;
}
encrip("Ni Hao", 3);

首先,您可以使用内置函数 indexOf,而不是内部for循环扫描整个alphabet数组:

alphabet.indexOf('K') // returns 10

其次,您需要在单独的变量中构建加密字符串。对于每个字母,获取字母表中该字母的索引,将密码偏移量参数添加到该索引,并将字母表中生成的字母添加到新字符串中。一个重要的步骤是,当您添加到字母的索引时,您希望确保生成的索引在alphabet数组的范围内。您可以使用%(模(运算符来执行此操作,该运算符会将高值包装回数组的开头。全文:

function encipher(input, offset) {
var alphabet = ["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 str = input.toUpperCase();
var result = '';
for (var i = 0; i < str.length; i++) {
letterIndex = alphabet.indexOf(str.charAt(i));
if (letterIndex === -1) {
result += str[i]; // if the letter isn't found in the alphabet, add it to the result unchanged
continue;
}
cipheredIndex = (letterIndex + offset) % alphabet.length; // wrap index to length of alphabet
result += alphabet[cipheredIndex];
}
console.log(result);
}
encipher('Ni Hao', 5); // output: 'SN MFT'

相关内容

  • 没有找到相关文章

最新更新