Convert integer into its character equivalent, where 0 => a, 1 => b, etc

前端 未结 12 811
无人共我
无人共我 2020-11-28 02:52

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.

12条回答
  •  温柔的废话
    2020-11-28 03:14

    A simple answer would be (26 characters):

    String.fromCharCode(97+n);
    

    If space is precious you could do the following (20 characters):

    (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:

    0123456789abcdefghijklmnopqrstuvwxyz
    ^         ^
    n        n+10
    

    By offsetting by 10 the characters start at a instead of 0.

    Not entirely sure about how fast running the two different examples client-side would compare though.

提交回复
热议问题