在 JavaScript 中将字符串映射到数字

javascriptweb developmentfront end technologyobject oriented programming更新于 2026/2/9 0:44:17

我们需要编写一个接受字符串的 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"

相关文章


有用资源