用 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"

更新於: 22-Oct-2020

686 次瀏覽

開始您的 職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.