用字母表中的位置替换字母 JavaScript

javascriptweb developmentobject oriented programming更新于 2025/9/28 18:52:17

我们需要编写一个函数,该函数接收一个字符串,删除其中的任何空格,将其转换为小写,并返回一个数字数组,该数组描述了英文字母表中相应字符的位置,字符串中的任何空格或特殊字符都应被忽略。

例如 −

Input → ‘Hello world!’
Output → [8, 5, 12, 12, 15, 23, 15, 18, 12, 4]

其代码为 −

示例

const str = 'Hello world!';
const mapString = (str) => {
   const mappedArray = [];
   str
   .trim()
   .toLowerCase()
   .split("")
   .forEach(char => {
      const ascii = char.charCodeAt();
      if(ascii >= 97 && ascii <= 122){
         mappedArray.push(ascii - 96);
      };
   });
   return mappedArray;
};
console.log(mapString(str));

输出

控制台中的输出将是 −

[
   8, 5, 12, 12, 15,
   23, 15, 18, 12, 4
]

相关文章


有用资源