嘗試為字串中的每個字元獲取數字 - JavaScript


我們需要編寫一個接受字串的 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"

更新日期:30-Sep-2020

178 次瀏覽

開啟你的 職業生涯

完成課程,獲得認證

開始
廣告
© . All rights reserved.