20

我正在尝试将数字转换为字母。我正在制作一个需要数字或数字和字母的 div 数组。所以1-3只是1-3。但是4-13需要是a/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>");
    }
}
4

3 回答 3

47

由于 97 是“a”的 ascii 值,而“a”的值为 3,因此您需要这样做才能将整数的值转换为字符:

if(i>=3){
    String.fromCharCode(94 + i);
}
于 2012-11-02T19:49:02.087 回答
26

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

于 2012-11-02T19:48:53.560 回答
4

你可以使用这个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    

于 2021-03-24T17:14:52.213 回答