将数字转换为字母javascript

Gam*_*bai 14 javascript implicit-conversion

我正在尝试将数字转换成字母.我正在制作一组需要数字或数字和字母的div.所以1-3只是1-3.但4-13需要是/ 4,b/5,c6等.有没有办法可以轻松地将这些数字转换成字母.也许将ascii值改变一定量?

     for(var i = 1; i < 33; i++){
    if( i < 4 || (i > 13 && i < 20) || i > 29){
        $('#teeth-diagram').append("<div class='tooth' id='" + i + "'>&nbsp;</div>");
    }else{
        $('#teeth-diagram').append("<div class='tooth' id='" + Letter goes here + "/" + i + "'>&nbsp;</div>");
    }
}
Run Code Online (Sandbox Code Playgroud)

Fis*_*sch 34

因为97是'a'的ascii值,而'a'的值是3,你需要这样做以获得转换为字符的整数的值:

if(i>=3){
    String.fromCharCode(94 + i);
}
Run Code Online (Sandbox Code Playgroud)


Luk*_*ker 16

是的你可以.使用var letter = String.fromCharCode(number); 要获得小写字母a,数字将为97,b将为98,依此类推.对于大写的A 65,B将是66,依此类推.请参阅此JSFiddle以获取示例


Dhe*_*Rao 7

您可以使用String.fromCharCode(x)该函数,只需传递正确的索引(例如:97 = a, 98 = b

const numberA = 1; // 1 = A, 2 = B,...., 26 = Z
const numberB = 2; 


//lowercase (start in CharCode 97)
console.log( String.fromCharCode(96 + numberA) ); //a
console.log( String.fromCharCode(96 + numberB) ); //b
   

console.log("------------");


//uppercase (start in CharCode 65)
console.log( String.fromCharCode(64 + numberA) ); //A
console.log( String.fromCharCode(64 + numberB) ); //B    
Run Code Online (Sandbox Code Playgroud)

  • 对于大写字母,我建议只使用起始点 64 而不是 96。对我来说,我使用这个: `//Index is base 0 so I use 65. getLetter(index: number): string { // String.fromCharCode(65 ) 返回(大写)A。接下来的 26 个字符是后续字母。返回 String.fromCharCode(65 + 索引); }` (2认同)

归档时间:

查看次数:

21241 次

最近记录:

13 年,2 月 前