一個簡單的例子:
aim: A,B,C,...,Z,AA,AB,AC.......AZ,BA,BB...BZ.
寫一個函數,給你一個數字你就能得出對應的列數,例如27對應AA,28對應AB
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>數字轉字母順序</title> 6 </head> 7 <body> 8 <div> 9 輸入數字:<input type = "text" class = "num"> 10 11 轉換: <button type = "button" onclick = "change()">轉換</button> 12 <br> 13 轉換后的字母順序:<span id = "resultString"></span> 14 </div> 15 </body> 16 <script> 17 var change = function () { 18 var num = document.getElementsByClassName("num")[0].value; 19 var stringName = ""; 20 if(num > 0) { 21 if(num >= 1 && num <= 26) { 22 stringName = String.fromCharCode(64 + parseInt(num)); 23 } else { 24 while(num > 26) { 25 var count = parseInt(num/26); 26 var remainder = num%26; 27 if(remainder == 0) { 28 remainder = 26; 29 count--; 30 stringName = String.fromCharCode(64 + parseInt(remainder)) + stringName; 31 } else { 32 stringName = String.fromCharCode(64 + parseInt(remainder)) + stringName; 33 } 34 num = count; 35 } 36 stringName = String.fromCharCode(64 + parseInt(num)) + stringName; 37 } 38 } 39 console.log(stringName); 40 document.getElementById("resultString").innerText = stringName; 41 } 42 </script> 43 </html>