根据JavaScript中的数组移动字符串字母

假设我们有一个仅包含小写英文字母的字符串,表示alphabets.For此问题的目的,我们将字母的单位移位定义为将该字母替换为字母中的后续字母(包括换行表示“ z”旁边是“ a”);

我们需要编写一个JavaScript函数,该函数以字符串str作为第一个参数,并以长度与str相同的数字arr作为第二个参数。我们的函数应该准备一个新字符串,在该字符串中原始字符串的字母被数组arr中存在的相应单位移位。

例如-

如果输入字符串和数组为-

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

那么输出应该是-

const output = '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