基于数组在 JavaScript 中转换字符串字母
假设我们有一个仅包含小写英语字母的字符串。为此问题,我们将字母的单位转换定义为将其替换为字母表中紧随其后的字母(包括环绕,即 '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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
安卓
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP