数字转字母顺序 JS实现

一个简单的例子:

 

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>

 

posted @ 2016-09-23 14:56  vasttian  阅读(2160)  评论(0编辑  收藏  举报