TextEncoder把字符串编码成字节
语法
const textEncoder = new TextEncoder()
textEncoder.encode(str,[destination])
str 编码的字符串
destination 把编码字节放到destination中,其必须是Uint8Array
TextDecoder把字节解码成字符串
语法
const textDecoder = new TextDecoder([label],[option])
- label 编码格式,默认为utf-8
- option 可选对象
- fatal 布尔值,为true则遇到无效字符抛出异常,为false(默认)则用字符\uFFFD替换无效字符
综合用例
const textEncoder = new TextEncoder();
const typeArray = textEncoder.encode("你好");
console.log(typeArray.BYTES_PER_ELEMENT); //1 说明用的是8位的typeArray
console.log(typeArray.byteLength); // 6 中文占3字节
const textDecoder = new TextDecoder();
console.log(textDecoder.decode(typeArray.slice(0, 3))); // 你