找到按下哪些號碼可以得到該單詞(與電話號碼數字問題相反)在 JavaScript 中


舊式鍵盤型手機中的數字到字母的對映關係如下:-

const mapping = {
   1: [],
   2: ['a', 'b', 'c'],
   3: ['d', 'e', 'f'],
   4: ['g', 'h', 'i'],
   5: ['j', 'k', 'l'],
   6: ['m', 'n', 'o'],
   7: ['p', 'q', 'r', 's'],
   8: ['t', 'u', 'v'],
   9: ['w', 'x', 'y', 'z']
};

我們需要編寫一個 JavaScript 函式,該函式接收一個字母字串並返回輸入該字串時按下的數字組合。

例如 −

如果字母串為 −

const str = 'mad';

那麼輸出號碼應為 −

const output = [6, 2, 3];

示例

程式碼如下 −

const mapping = {
   1: [],
   2: ['a', 'b', 'c'],
   3: ['d', 'e', 'f'],
   4: ['g', 'h', 'i'],
   5: ['j', 'k', 'l'],
   6: ['m', 'n', 'o'],
   7: ['p', 'q', 'acc', 's'],
   8: ['t', 'u', 'v'],
   9: ['w', 'x', 'y', 'z']
};
const convertToNumeral = (str = '') => {
   const entries = Object.entries(mapping);
   const res = entries.reduce((acc, [v, letters]) => {
      letters.forEach(l => acc[l] = +v);
      return acc;
   }, {});
   const result = Array.from(str, (el) => {
      return res[el];
   });
   return result;
};
console.log(convertToNumeral('mad'))

輸出

而控制檯中的輸出將為 −

[ 6, 2, 3 ]

更新於: 2020-11-24

109 次瀏覽

啟動你的 職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.