เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับสตริงเป็นอาร์กิวเมนต์แรกและตัวเลขเป็นอาร์กิวเมนต์ที่สอง
ฟังก์ชันควรแทนที่ตัวอักษรแต่ละตัวในสตริงโดยเลื่อนตัวอักษรขึ้นตามตัวเลขที่กำหนด
การขยับควรวนกลับมาที่จุดเริ่มต้นหรือจุดสิ้นสุดของตัวอักษร เช่น a ควรตามหลัง z แทนที่จะเป็น undefined หรือผลลัพธ์ที่เป็นโมฆะ
ตัวอย่าง
const str = 'this is a str';
const encryptString = (str = '', num = 1) => {
const alphabet = "abcdefghijklmnopqrstuvwxyz".split("");
str = str.toLowerCase();
let res = "";
for (let i = 0; i < str.length; i++) {
const letter = str[i];
if (alphabet.indexOf(letter) === -1) {
res += letter;
continue;
}
let index = alphabet.indexOf(letter) + num % 26;
if (index > 25){
index -= 26;
};
if (index < 0){
index += 26;
};
if(str[i] === str[i].toUpperCase()){
res += alphabet[index].toUpperCase();
}else{ res += alphabet[index];
};
}
return res;
};
console.log(encryptString(str, 4)); ผลลัพธ์
และผลลัพธ์ในคอนโซลจะเป็น −
xlmw mw e wxv