Javascript 将整数转换为其等效的字符,其中 0 => a、1 => b 等
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3145030/
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
Convert integer into its character equivalent, where 0 => a, 1 => b, etc
提问by VIVA LA NWO
I want to convert an integer into its character equivalent based on the alphabet. For example:
我想根据字母表将整数转换为其等效的字符。例如:
0 => a
1 => b
2 => c
3 => d
etc. I could build an array and just look it up when I need it but I'm wondering if there's a built in function to do this for me. All the examples I've found via Google are working with ASCII values and not a character's position in the alphabet.
等等。我可以构建一个数组,并在需要时查找它,但我想知道是否有内置函数可以为我执行此操作。我通过 Google 找到的所有示例都使用 ASCII 值,而不是字符在字母表中的位置。
回答by Daniel Vandersluis
Assuming you want lower case letters:
假设你想要小写字母:
var chr = String.fromCharCode(97 + n); // where n is 0, 1, 2 ...
97 is the ASCII code for lower case 'a'. If you want uppercase letters, replace 97 with 65 (uppercase 'A'). Note that if n > 25, you will get out of the range of letters.
97 是小写字母“a”的 ASCII 码。如果需要大写字母,请将 97 替换为 65(大写“A”)。请注意,如果n > 25,您将超出字母范围。
回答by mbq
Will be more portable in case of extending to other alphabets:
在扩展到其他字母的情况下将更便携:
char='abcdefghijklmnopqrstuvwxyz'[code]
or, to be more compatible (with our beloved IE):
或者,为了更兼容(与我们心爱的 IE):
char='abcdefghijklmnopqrstuvwxyz'.charAt(code);
回答by z0r
If you don't mind getting multi-character strings back, you can support arbitrary positive indices:
如果您不介意取回多字符串,则可以支持任意正索引:
function idOf(i) {
return (i >= 26 ? idOf((i / 26 >> 0) - 1) : '') + 'abcdefghijklmnopqrstuvwxyz'[i % 26 >> 0];
}
idOf(0) // a
idOf(1) // b
idOf(25) // z
idOf(26) // aa
idOf(27) // ab
idOf(701) // zz
idOf(702) // aaa
idOf(703) // aab
(Not thoroughly tested for precision errors :)
(没有彻底测试精度错误:)
回答by Dan
A simple answer would be (26 characters):
一个简单的答案是(26 个字符):
String.fromCharCode(97+n);
If space is precious you could do the following (20 characters):
如果空间很宝贵,您可以执行以下操作(20 个字符):
(10+n).toString(36);
Think about what you could do with all those extra bytes!
想想你可以用所有这些额外的字节做什么!
How this works is you convert the number to base 36, so you have the following characters:
其工作原理是将数字转换为以 36 为基数的数字,因此您具有以下字符:
0123456789abcdefghijklmnopqrstuvwxyz
^ ^
n n+10
By offsetting by 10 the characters start at ainstead of 0.
通过偏移 10,字符开始于a而不是0。
Not entirely sure about how fast running the two different examples client-side would compare though.
不完全确定客户端运行这两个不同示例的速度会比较快。
回答by hundredwatt
Javascript's String.fromCharCode(code1, code2, ..., codeN) takes an infinite number of arguments and returns a string of letters whose corresponding ASCII values are code1, code2, ... codeN. Since 97 is 'a' in ASCII, we can adjust for your indexing by adding 97 to your index.
Javascript 的 String.fromCharCode(code1, code2, ..., codeN) 接受无限数量的参数并返回一串字母,其对应的 ASCII 值为 code1, code2, ... codeN。由于 97 在 ASCII 中是“a”,我们可以通过将 97 添加到您的索引来调整您的索引。
function indexToChar(i) {
return String.fromCharCode(i+97); //97 in ASCII is 'a', so i=0 returns 'a',
// i=1 returns 'b', etc
}
回答by junvar
I don't like all the solutions that use magic numbers like 97or 36.
我不喜欢所有使用魔术数字的解决方案,例如97或36。
const A = 'A'.charCodeAt(0);
let numberToCharacter = number => String.fromCharCode(A + number);
let characterToNumber = character => character.charCodeAt(0) - A;
this assumes uppercase letters and starts 'A' at 0.
这假定大写字母并从 0 开始 'A'。
回答by James Westgate
Use String.fromCharCode. This returns a string from a Unicode value, which matches the first 128 characters of ASCII.
使用String.fromCharCode. 这将从 Unicode 值返回一个字符串,该字符串与 ASCII 的前 128 个字符匹配。
var a = String.fromCharCode(97);
回答by gblazex
There you go: (a-zA-Z)
你去吧:(a-zA-Z)
function codeToChar( number ) {
if ( number >= 0 && number <= 25 ) // a-z
number = number + 97;
else if ( number >= 26 && number <= 51 ) // A-Z
number = number + (65-26);
else
return false; // range error
return String.fromCharCode( number );
}
input: 0-51, or it will return false (range error);
输入:0-51,否则返回false(范围错误);
OR:
或者:
var codeToChar = function() {
var abc = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");
return function( code ) {
return abc[code];
};
})();
returns undefined in case of range error. NOTE: the array will be created only once and because of closure it will be available for the the new codeToChar function. I guess it's even faster then the first method (it's just a lookup basically).
在范围错误的情况下返回 undefined。注意:该数组将仅创建一次,并且由于关闭,它将可用于新的 codeToChar 函数。我想它比第一种方法更快(基本上只是查找)。
回答by Pandem1c
The only problemo with @mikemaccana's great solution is that it uses the binary >> operator which is costly, performance-wise. I suggest this modification to his great work as a slight improvement that your colleagues can perhaps read more easily.
@mikemaccana 的伟大解决方案的唯一问题是它使用了二进制 >> 运算符,这在性能方面代价高昂。我建议对他的伟大作品进行这种修改,作为一个小小的改进,您的同事或许可以更轻松地阅读。
const getColumnName = (i) => {
const previousLetters = (i >= 26 ? getColumnName(Math.floor(i / 26) -1 ) : '');
const lastLetter = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[i % 26];
return previousLetters + lastLetter;
}
Or as a one-liner
或作为单线
const getColumnName = i => (i >= 26 ? getColumnName(Math.floor(i / 26) -1 ) : '') + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[i % 26];
Example:
例子:
getColumnName(0); // "A"
getColumnName(1); // "B"
getColumnName(25); // "Z"
getColumnName(26); // "AA"
getColumnName(27); // "AB"
getColumnName(80085) // "DNLF"
回答by Kamil Kie?czewski
Try
尝试
(n+10).toString(36)
chr = n=>(n+10).toString(36);
for(i=0; i<26; i++) console.log(`${i} => ${ chr(i) }`);

