尝试获取字符串中每个字符的数字 - JavaScript

javascriptweb developmentfront end technologyobject oriented programming更新于 2025/12/31 21:00:17

我们需要编写一个 JavaScript 函数来接收一个字符串。它应该打印出字符串中每个对应字母的每个数字。

例如,

a = 1
b = 2
c = 3
d = 4
e = 5
.
.
.
Y = 25
Z = 26

因此,如果输入是"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"

相关文章


有用资源