Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

เลื่อนตัวอักษรในสตริงตามอาร์เรย์จำนวน (Character Shifting) ใน JavaScript

ปัญหา

ได้รับสตริง str และอาร์เรย์ arr ความยาวเท่ากัน แต่ละตัวอักษรใน str จะถูกเลื่อนไปข้างหน้าตามจำนวนใน arr (วนรอบ z→a)

ตัวอย่าง

const str = 'dab'; 
const arr = [1, 4, 6];

d+1=e, a+4=e, b+6=h → ผลลัพธ์ 'eeh'

โค้ดตัวอย่าง

const str = 'dab'; 
const arr = [1, 4, 6]; 
const shiftString = (str = '', arr = []) => { 
  const legend = '-abcdefghijklmnopqrstuvwxyz'; 
  let res = ''; 
  for(let i = 0; i < arr.length; i++){ 
    const el = str[i]; 
    const shift = arr[i]; 
    const index = legend.indexOf(el); 
    let newIndex = index + shift; 
    newIndex = newIndex <= 26 ? newIndex : newIndex % 26; 
    res += legend[newIndex]; 
  } 
  return res; 
}; 
console.log(shiftString(str, arr));

ผลลัพธ์

eeh