在JavaScript中将字符串映射到数字
我们需要编写一个包含字符串的JavaScript函数。它应该为字符串中的每个对应字母打印出每个数字。
例如:
a = 1 b = 2 c = 3 d = 4 e =5 . . . y = 25 z = 25
注意:删除任何特殊字符和空格。
因此,如果输入为-
"hello man"
那么输出应该是-
"8,5,12,12,15,13,1,14"
示例
为此的代码将是-
const str = 'hello man';
const charPosition = str => {
str = str.split('');
const arr = [];
const alpha = /^[A-Za-z]+$/;
for(i=0; i < str.length; i++){
if(str[i].match(alpha)){
const num = str[i].charCodeAt(0) - 96;
arr.push(num);
}else{
continue;
};
};
return arr.toString();
}
console.log(charPosition(str));输出结果
控制台中的输出将为-
"8,5,12,12,15,13,1,14"
热门推荐
10 祝女儿简短祝福语大全
11 大学新年祝福语简短创意
12 元旦适合的祝福语简短
13 朋友出远门祝福语简短
14 初六简短的祝福语
15 祝男孩生日祝福语简短
16 同事调离的祝福语简短
17 拜年红包的祝福语简短
18 妈妈生日祝福语简短励志