设置字母变量的优雅方式,如Excel列

时间:2017-01-12 11:08:28

标签: javascript

我正在寻找一种方法,让变量alpha增量如下:x=0 -> alpha = "A"; x=1 -> alpha = "B"; ...... x=25 -> alpha = "Z"; x=26 -> alpha = "AA"; x=27 -> alpha = "AB"

3 个答案:

答案 0 :(得分:2)

<强> EDITED

好的抱歉,我一开始并不理解您的需求。这是一个有效的代码。

试试这个:

var x = 807;
var alpha = '';
var alphabetLength = 26;


var y = x.toString(alphabetLength);
chars = y.split('');
for (var i=0; i < chars.length; i++ ) {
	var charFactor = 65;
	var curChar = chars[i];
	if (isNaN(curChar)) {
	
		alpha += String.fromCharCode(curChar.toUpperCase().charCodeAt() + 10);
	} else {
		if ( i < chars.length-1) {
			charFactor--;
		}
		alpha += String.fromCharCode(parseInt(curChar) + charFactor);
	}
}

console.log(alpha)

答案 1 :(得分:1)

使用String.fromCharCode方法并使用char代码生成字符串。

// initialize as empty string
var alpha = '';
// iterate upto value is reaching -1 since index starts from 0
while (x > -1) {
  // get charactor by finding remainder 
  // and concatenate it with alpha
  alpha = String.fromCharCode(65 + x % 26) + alpha;
  // update value of variable x 
  // decrement by 1 since index starts from 0
  x = Math.floor(x / 26) - 1;
}

[1, 28, 25, 26, 27, 3335, 12, 10, 3, 6, 0].forEach(function(x) {
  var alpha = '';
  while (x > -1) {
    alpha = String.fromCharCode(65 + x % 26) + alpha;
    x = Math.floor(x / 26) - 1;
  }
  console.log(alpha);
});

答案 2 :(得分:1)

您可以使用基座toString的{​​{1}}转换为想要的字母。

&#13;
&#13;
36
&#13;
function convert(n) {
    var result = '';
    do {
        result = (n % 26 + 10).toString(36) + result;
        n = Math.floor(n / 26) - 1;
    } while (n >= 0)
    return result.toUpperCase();
}

//           A  B   Z  AA  AB   CZ   DXH
console.log([0, 1, 25, 26, 27, 103, 3335].map(convert));
&#13;
&#13;
&#13;