在 JavaScript 中用第 n 个字母替换字母
javascriptweb developmentfront end technologyobject oriented programming
我们需要编写一个 JavaScript 函数,该函数接受一个字母字符串和一个数字(例如 n)。然后我们应该返回一个新字符串,其中所有字符都被替换为位于其旁边第 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 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

