由于项目需求,需要实现 A B C ...Y Z AA AB...等等一次递增,默认0是A。简单写了一下,希望可以帮助有需要的人
function numToChar(num){
let str = "";
while(num >= 0){
let tmp = num % 26;
if(tmp < 26){
str = String.fromCharCode(tmp + 65) + str;
} else {
str = String.fromCharCode(tmp - 26 + 65) + str;
}
num = Math.floor(num / 26) - 1;
}
return str;
}
function charToNum(str){
let num = 0;
for(let idx = str.length; idx > 0; idx --){
if(idx == str.length){
num += str.charAt(idx - 1).charCodeAt(0) - 65;
} else {
num += Math.pow(26, str.length - idx) *
(str.charAt(idx - 1).charCodeAt(0) - 65 + 1);
}
}
return num;
}