เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับสตริงและเปลี่ยนตัวอักษรทุกตัวในสตริงจากตัวอักษรภาษาอังกฤษเป็นองค์ประกอบที่ตามมา
ตัวอย่างเช่น หากสตริงคือ −
const str = 'how are you';
ผลลัพธ์
จากนั้นผลลัพธ์ควรเป็น −
const output = 'ipx bsf zpv'
ดังนั้น เรามาเขียนโค้ดสำหรับฟังก์ชันนี้กัน −
ตัวอย่าง
รหัสสำหรับสิ่งนี้จะเป็น −
const str = 'how are you';
const isAlpha = code => (code >= 65 && code <= 90) || (code >= 97 && code <= 122);
const isLast = code => code === 90 || code === 122;
const nextLetterString = str => {
const strArr = str.split('');
return strArr.reduce((acc, val) => {
const code = val.charCodeAt(0);
if(!isAlpha(code)){
return acc+val;
};
if(isLast(code)){
return acc+String.fromCharCode(code-25);
};
return acc+String.fromCharCode(code+1);
}, '');
};
console.log(nextLetterString(str)); ผลลัพธ์ในคอนโซลจะเป็น -
ipx bsf zpv