JavaScript 中表示数字的字母
我们需要编写一个 JavaScript 函数,该函数接受一个表示数字的任意可变长度的字符串。
我们的函数应该将数字字符串转换为相应的字母字符串。
例如 - 如果数字字符串为 -
const str = '78956';
那么输出应该是 -
const output = 'ghief';
如果数字字符串为 -
const str = '12345';
那么输出字符串应该是 -
const output = 'lcde';
请注意,我们没有单独将 1 和 2 转换为字母,因为 12 也表示字母。因此,在编写函数时,我们必须考虑这种情况。
我们在此处假定数字字符串不包含 0,如果它包含,则会将 0 映射到本身。
示例
让我们写出此函数的代码 -
const str = '12345';
const str2 = '78956';
const convertToAlpha = numStr => {
const legend = '0abcdefghijklmnopqrstuvwxyz';
let alpha = '';
for(let i = 0; i < numStr.length; i++){
const el = numStr[i], next = numStr[i + 1];
if(+(el + next) <= 26){
alpha += legend[+(el + next)];
i++;
}
else{
alpha += legend[+el];
};
};
return alpha;
};
console.log(convertToAlpha(str));
console.log(convertToAlpha(str2));输出
在控制台中的输出将为 -
lcde ghief
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP