ArrayBuffer转换字符串
const ab2Str = function(arrayBuffer:ArrayBuffer):string{
const textDecoder = new TextDecoder();
const data = textDecoder.decode(arrayBuffer);
return data;
}
TextDecoder方法在微信开发者工具中是可以正常运行的,但是在真机中,报错:TextDecoder没有定义
最简单兼容做法:定义TextDecoder函数,实现decode方法,并支持中文
(function (global) {
/**
* 兼容TextDecoder
*/
if (typeof global.TextDecoder !== 'function') {
function _TextDecoder() {}
_TextDecoder.prototype.decode = function (arrayBuffer) {
// @ts-ignore
return decodeURIComponent(escape(String.fromCharCode.apply(null, new Uint8Array(arrayBuffer))));
};
// @ts-ignore
global.TextDecoder = _TextDecoder;
}
})(this || window || globalThis);
字符串转换ArrayBuffer
const str2Ab = function(str:string):ArrayBuffer{
const textEncoder = new TextEncoder();
const data = textEncoder.encode(str);
return data;
}
TextEncoder方法在微信开发者工具中是可以正常运行的,但是在真机中,报错:TextEncoder没有定义
最简单兼容做法:定义TextEncoder函数,实现encode方法
(function (global) {
/**
* 兼容TextEncoder
*/
if (typeof global.TextEncoder !== 'function') {
function _TextEncoder() {}
_TextEncoder.prototype.encode = function (str) {
var data = unescape(encodeURIComponent(str))
.split('')
.map(val => val.charCodeAt(0));
return typeof Uint8Array == 'function' ? new Uint8Array(data) : data;
};
// @ts-ignore
global.TextEncoder = _TextEncoder;
}
})(this || window || globalThis);
微信小程序更多兼容方法,请查看资源:我的资源