将整数转换为等效的 alpha 有序列表
我需要一个函数将整数转换为等效的 alpha 有序列表索引。例如:
1 = a
2 = b
.
.
.
26 = z
27 = AA
28 = ab
.
.
等等。
目前,我有以下几乎工作,但某处存在一个小逻辑错误,使其不太正确(它会斧头,哎,<强>bz,ba,bb,bc...):
function intToAlpha( int ) {
var asciiStart = 97,
alphaMax = 26,
asciiCode,
char,
alpha = '',
place,
num,
i;
for ( i = 0; Math.pow(alphaMax, i) < int; i++ ) {
place = Math.pow(alphaMax, i);
num = Math.floor( ( int / place ) % alphaMax);
asciiCode = ( num == 0 ? alphaMax : num ) + asciiStart - 1;
char = String.fromCharCode(asciiCode);
alpha = char + alpha;
}
return alpha;
}
for (i = 1; i < 300; i++) {
console.log( i + ': ' + intToAlpha(i) );
}
I need to a function to convert an integer to the equivalent alpha ordered list index. For example:
1 = a
2 = b
.
.
.
26 = z
27 = aa
28 = ab
.
.
etc.
Currently I have the following which almost works but there's a small logic error somewhere that makes it not quite get it right (it goes ax, ay, bz, ba, bb, bc...):
function intToAlpha( int ) {
var asciiStart = 97,
alphaMax = 26,
asciiCode,
char,
alpha = '',
place,
num,
i;
for ( i = 0; Math.pow(alphaMax, i) < int; i++ ) {
place = Math.pow(alphaMax, i);
num = Math.floor( ( int / place ) % alphaMax);
asciiCode = ( num == 0 ? alphaMax : num ) + asciiStart - 1;
char = String.fromCharCode(asciiCode);
alpha = char + alpha;
}
return alpha;
}
for (i = 1; i < 300; i++) {
console.log( i + ': ' + intToAlpha(i) );
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
该函数在 NVu/Kompozer/SeaMonkey Composer 中使用,稍加调整即可直接生成小写字母:
This function is used in NVu/Kompozer/SeaMonkey Composer, with a small tweak to generate lower case directly:
您需要确保在获取 mod 时使用正确的值。
You need to make sure that you use the correct value when taking the mod.
不久前,我在 SQL 中需要同样的东西,所以我问(并回答)了这个问题 多基转换 - 使用 URL 缩短器的所有组合。
让它变得复杂的是,它不是直接的基数转换,因为没有代表零数字的字符。
我将 SQL 函数转换为 Javascript:
演示: http://jsfiddle.net/Guffa/mstBe/
A while back I needed the same thing in SQL, so I asked (and answered) the question Multi-base conversion - using all combinations for URL shortener.
The thing that is making it complicated is that it's not a straight base conversion, as there is no character representing the zero digit.
I converted the SQL function into Javascript:
Demo: http://jsfiddle.net/Guffa/mstBe/