【问题标题】:More appropriate way to loop over hex values循环十六进制值的更合适的方法
【发布时间】:2014-03-01 00:59:00
【问题描述】:

我正在使用图标字体填充具有不同符号的容器。我想知道是否有比创建自定义数组更好的方法来遍历十六进制值并这样做:

var hexPlaceValue1=0, hexPlaceValue2=0;
var hexArray = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'];

for(var i=0;i through something;i++){
    if(hexPlaceValue1 == 15) {
        var $glyph = $('<div class="glyph" data-glyph-index="' + i + '">&#xe' + String('00' + hexArray[hexPlaceValue2] + hexArray[hexPlaceValue1]).slice(-3) + ';</div>');
        hexPlaceValue1 = 0;
        hexPlaceValue2++;
    } else {
        var $glyph = $('<div class="glyph" data-glyph-index="' + i + '">&#xe' + String('00' + hexArray[hexPlaceValue2] + hexArray[hexPlaceValue1]).slice(-3) + ';</div>');
        hexPlaceValue1++;
    }
}

显然,如果引入更多图标,这可能会导致问题(当然,它必须很多。)我只是想知道是否有更有效的方法来做到这一点。

【问题讨论】:

    标签: javascript jquery optimization hex logic


    【解决方案1】:

    Javascript 和大多数(所有?)编程语言一样,知道如何处理十六进制。

    for (i=0x0; i < 0x30; i++) { print("0x0" + i.toString(16) +" = " + i) }
    

    输出:

    0x00 = 0
    0x01 = 1
    0x02 = 2
    0x03 = 3
    0x04 = 4
    0x05 = 5
    0x06 = 6
    0x07 = 7
    0x08 = 8
    0x09 = 9
    0x0a = 10
    0x0b = 11
    0x0c = 12
    0x0d = 13
    0x0e = 14
    0x0f = 15
    0x010 = 16
    [...]
    0x026 = 38
    0x027 = 39
    0x028 = 40
    0x029 = 41
    0x02a = 42
    0x02b = 43
    0x02c = 44
    0x02d = 45
    0x02e = 46
    0x02f = 47
    

    然后可以使用填充,请参阅google 或这个问题:Pad a number with leading zeros in JavaScript

    【讨论】:

      【解决方案2】:

      根据您的 for 循环中的逻辑,它看起来基本上就像您想要做的那样:

      for(var i=0;i through something;i++) {
         var hex = '&#x' + (0xe000|i).toString(16);
         var $glyph = $('<div class="glyph" data-glyph-index="'+i+'">'+hex+';</div>');
      }
      

      只要i&lt;4096 (0x1000),那么最重要的十六进制数字就保持为e

      【讨论】:

      • 你能解释一下这个语法吗:(0ex000|i)
      • @jefffabiny 前面有0x 表示hexadecimal number|bitwise OR 运算符。基本上(0xe000|i).toString(16) 将采用i,将其转换为十六进制,0 填充为3 个字符,并在前面加上e。和你的循环一样。希望对您有所帮助。
      【解决方案3】:

      您可以像这样迭代 ascii 代码,而不是硬编码数组:

      // Instead of this
      // var hexArray = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'];
      
      // You can use this:
      for (var i=48; i<71; i++){
          console.log( i, String.fromCharCode(i) );
          // Skip 58 to 64 char codes as they are non alphanumeric
          if (i == 57) i =64;
      }
      

      你可以在网上找到char码表,这里有一张link

      【讨论】:

      • 他使用&amp;#x0000;表示法是因为他使用的是字体,字体可能有绘图< 32(不可打印)或HTML中禁止的另一个字符(他不限于字母数字字符的AFAWK)。他不能只是简单地使用String.fromCharCode
      • 我知道,我刚刚添加了一个如何替换初始硬编码数组的示例。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-03
      • 2016-07-25
      • 2018-07-26
      • 1970-01-01
      • 1970-01-01
      • 2014-10-05
      • 2014-02-19
      相关资源
      最近更新 更多