javascript 将数字转换为 26 个字符以外的字母

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8240637/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 02:45:51  来源:igfitidea点击:

Convert numbers to letters beyond the 26 character alphabet

javascriptjquery

提问by Chris Spittles

I'm creating some client side functions for a mappable spreadsheet export feature.

我正在为可映射的电子表格导出功能创建一些客户端函数。

I'm using jQuery to manage the sort order of the columns, but each column is ordered like an Excel spreadsheet i.e. a b c d e......x y z aa ab ac ad etc etc

我正在使用 jQuery 来管理列的排序顺序,但每列的排序方式都类似于 Excel 电子表格,即 abcd e......xyz aa a b ac ad 等

How can I generate a number as a letter? Should I define a fixed array of values? Or is there a dynamic way to generate this?

如何将数字生成为字母?我应该定义一个固定的值数组吗?或者有没有一种动态的方式来生成这个?

回答by georg

I think you're looking for something like this

我想你正在寻找这样的东西

    function colName(n) {
        var ordA = 'a'.charCodeAt(0);
        var ordZ = 'z'.charCodeAt(0);
        var len = ordZ - ordA + 1;
      
        var s = "";
        while(n >= 0) {
            s = String.fromCharCode(n % len + ordA) + s;
            n = Math.floor(n / len) - 1;
        }
        return s;
    }

// Example:

    for(n = 0; n < 125; n++)
            document.write(n + ":" + colName(n) + "<br>");

回答by haynar

You can use code like this, assuming that numberscontains the numbers of your columns. So after this code you'll get the string names for your columns:

您可以使用这样的代码,假设其中numbers包含您的列数。因此,在此代码之后,您将获得列的字符串名称:

var letters = ['a', 'b', 'c', ..., 'z'];
var numbers = [1, 2, 3, ...];
var columnNames = [];
for(var i=0;i<numbers.length;i++) {
    var firstLetter = parseInt(i/letters.length) == 0 ? '' : letters[parseInt(i/letters.length)];
    var secondLetter = letters[i%letters.length-1];
    columnNames.push(firstLetter + secondLetter);
}