數字轉字母順序 JS實現

一個簡單的例子:


aim: A,B,C,...,Z,AA,AB,AC.......AZ,BA,BB...BZ.

寫一個函數,給你一個數字你就能得出對應的列數,例如27對應AA,28對應AB

代碼如下:
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>數字轉字母順序</title>
</head>
<body>
  <div>
    輸入數字:<input type = "text" class = "num">
      
    轉換: <button type = "button" onclick = "change()">轉換</button>
    <br>
    轉換後的字母順序:<span id = "resultString"></span>
  </div>
</body>
<script>
  var change = function () {
    var num = document.getElementsByClassName("num")[0].value;
    var stringName = "";
    if(num > 0) {
      if(num >= 1 && num <= 26) {
        stringName = String.fromCharCode(64 + parseInt(num));
      } else {
        while(num > 26) {
          var count = parseInt(num/26);
          var remainder = num%26;
          if(remainder == 0) {
            remainder = 26;
            count--;
            stringName = String.fromCharCode(64 + parseInt(remainder)) + stringName;
          } else {
            stringName = String.fromCharCode(64 + parseInt(remainder)) + stringName;
          }
          num = count;
        }
        stringName = String.fromCharCode(64 + parseInt(num)) + stringName;
      }
    }
    console.log(stringName);
    document.getElementById("resultString").innerText  = stringName;
  }
</script>
</html>




發佈了852 篇原創文章 · 獲贊 1848 · 訪問量 137萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章