【问题标题】:String encoding when constructing a Blob构造 Blob 时的字符串编码
【发布时间】:2015-02-22 00:30:56
【问题描述】:

我知道 JavaScript 字符串 are usually 编码为 with an encoding taking at least two bytes per character(UTF-16 或 UCS-2)。

但是,在构建 Blob 时,似乎使用了不同的编码,因为当我将其读取为 ArrayBuffer 时,返回的缓冲区长度为 3 表示欧元符号。

var b = new Blob(['€']);

【问题讨论】:

    标签: javascript encoding utf-8


    【解决方案1】:

    根据W3C,它是UTF-8编码的。

    演示:

    // Create a Blob with an Euro-char (U+20AC)
    var b = new Blob(['€']);
    var fr = new FileReader();
    
    fr.onload = function() {
      ua = new Uint8Array(fr.result);
      // This will log "3|226|130|172"
      //                  E2  82  AC
      // In UTF-16, it would be only 2 bytes long
      console.log(
        fr.result.byteLength + '|' + 
        ua[0]  + '|' + 
        ua[1] + '|' + 
        ua[2] + ''
      );
    };
    fr.readAsArrayBuffer(b);

    JSFiddle 上玩。

    【讨论】:

      猜你喜欢
      • 2012-06-09
      • 2020-07-26
      • 1970-01-01
      • 1970-01-01
      • 2017-05-05
      • 1970-01-01
      • 1970-01-01
      • 2019-12-23
      • 2023-01-03
      相关资源
      最近更新 更多