用JavaScript中的第n个前向字母替换字母
我们需要编写一个包含字母字符串和数字(例如n)的JavaScript函数。然后,我们应该返回一个新字符串,在该字符串中,所有字符在其旁边的n个字母处都被相应的字母替换。
例如,如果字符串和数字为-
const str = 'abcd';const n = 2;
那么输出应该是-
const output = 'cdef';
示例
为此的代码将是-
const str = 'abcd';const n = 2;
const replaceNth = (str, n) => {
const alphabet = 'abcdefghijklmnopqrstuvwxyz';
let i, pos, res = '';
for(i = 0; i < str.length; i++){
pos = alphabet.indexOf(str[i]);
res += alphabet[(pos + n) % alphabet.length];
};
return res;
};
console.log(replaceNth(str, n));
输出结果
控制台中的输出将是-
cdef
以上是 用JavaScript中的第n个前向字母替换字母 的全部内容, 来源链接: utcz.com/z/330854.html