用A,B,C,D而不是0,1,2,3,...用JavaScript [英] Count with A, B, C, D instead of 0, 1, 2, 3, ... with JavaScript
问题描述
这可能是一个不寻常的请求,但对于我的脚本,我需要一个函数,按字母而不是数字递增。例如:
This is probably an unusual request, but for my script I need a function that increments by letter instead of number. For example:
这是一个数字示例:
var i = 0;
while(condition){
window.write('We are at '+i);
++i;
}
本质上,我想计算字母,如Microsoft Excel,数字。因此,我不需要打印我们在0,我们在1,我们在2等,我需要打印我们在A,我们在B,我们在C等。
Essentially, I want to count with letters, like Microsoft Excel does, instead of numbers. So instead of printing "We are at 0", "We are at 1", "We are at 2", etc., I need to print "We are at A", "We are at B", "We are at C", etc.
为了模仿Excel(我可以想到的唯一例子),在达到索引25(Z)之后,我们可以移动到AA 'AB','AC'等。
To mimic Excel (the only example I can think of), after reaching index 25 (Z), we could move on to 'AA', 'AB', 'AC', etc.
所以它会工作得很好:
var i = 0;
while(condition){
window.write('We are at '+toLetter(i));
++i;
}
更好的是,如果有人能写一个函数,数字,即toNumber('A')= 0或toNumber('DC')= 107(我想)。
Even better if somebody can write a function that then converts a letter back into a digit, i.e. toNumber('A') = 0 or toNumber('DC') = 107 (I think).
谢谢!
推荐答案
这里有一个简单的递归函数将数字转换为字母。
Here's a simple recursive function to convert the numbers to letters.
这是一个基于的,所以1是A,26是Z,27是AA。
It's one-based, so 1 is A, 26 is Z, 27 is AA.
function toLetters(num) {
"use strict";
var mod = num % 26,
pow = num / 26 | 0,
out = mod ? String.fromCharCode(64 + mod) : (--pow, 'Z');
return pow ? toLetters(pow) + out : out;
}
这里有一个匹配函数将字符串转换回数字:
Here's a matching function to convert the strings back to numbers:
function fromLetters(str) {
"use strict";
var out = 0, len = str.length, pos = len;
while (--pos > -1) {
out += (str.charCodeAt(pos) - 64) * Math.pow(26, len - 1 - pos);
}
return out;
}
测试: http://jsfiddle.net/St6c9/
这篇关于用A,B,C,D而不是0,1,2,3,...用JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!