1
0
mirror of https://github.com/ruanyf/es6tutorial.git synced 2025-05-29 05:42:20 +00:00

docs(ArrayBuffer): optimize ab2str()

This commit is contained in:
waiting 2017-10-14 16:01:38 +08:00
parent 2a82f81022
commit 143a1e4b13
No known key found for this signature in database
GPG Key ID: 2C7023E12106AFFF

View File

@ -452,9 +452,19 @@ Float64Array.BYTES_PER_ELEMENT // 8
```javascript
// ArrayBuffer转为字符串参数为ArrayBuffer对象
function ab2str(buf) {
if (buf && buf.byteLength < 128000) { // limit max length avoid overhead
return String.fromCharCode.apply(null, new Uint16Array(buf));
}
const len = bufView.byteLength;
const bstr = new Array(len);
const bufView = new Uint16Array(buf);
for (let i = 0; i < len; i++) {
bstr[i] = String.fromCharCode.call(null, bufView[i]);
}
return bstr.join('');
}
// 字符串转为ArrayBuffer对象参数为字符串
function str2ab(str) {
const buf = new ArrayBuffer(str.length * 2); // 每个字符占用2个字节