【问题标题】:convert number to letter javascript将数字转换为字母javascript
【发布时间】:2012-11-02 19:43:47
【问题描述】:

我正在尝试将数字转换为字母。我正在制作一个需要数字或数字和字母的 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>");
    }
}

【问题讨论】:

  • 我想我被误解了。我不想在每个 div 上输入 a、b、c、d。我只是希望它动态完成。所以如果我可以将 4 in 转换为 a 并将 5 in 转换为 b 那就太好了
  • 这个应该会有所帮助 - [从 ascii 值创建字符串或字符][1] [1]:stackoverflow.com/questions/602020/…
  • @lserni 不是没有 jalaj.net/2007/03/08/asc-and-chr-in-javascript 之类的东西... javascript 中的 ordchr 是什么?
  • 对不起@Ian,我把它们当作快捷方式,但经常忘记它们不是标准的。我已经编辑了我的评论,但为时已晚:-)

标签: javascript implicit-conversion


【解决方案1】:

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

if(i>=3){
    String.fromCharCode(94 + i);
}

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      您可以为此使用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    

      【讨论】:

      • 对于大写,我建议只使用 64 而不是 96 的起点。对我来说,我使用这个://Index is base 0 so I use 65. getLetter(index: number): string { // String.fromCharCode(65) returns (capital) A. The next 26 chars is the subsequent letter. return String.fromCharCode(65 + index); }
      猜你喜欢
      • 2015-01-24
      • 1970-01-01
      • 2015-03-08
      • 2016-07-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多