在 ArrayBuffer 中存储一个 json 对象

store a json object in ArrayBuffer

想要在 ArrayBuffer

中存储一个 json 对象
function stringToUint(string) {
    var string = btoa(unescape(encodeURIComponent(string))),
        charList = string.split(''),
        uintArray = [];
    for (var i = 0; i < charList.length; i++) {
        uintArray.push(charList[i].charCodeAt(0));
    }
    return new Uint8Array(uintArray);
}

function uintToString(uintArray) {
    var encodedString = String.fromCharCode.apply(null, uintArray),
        decodedString = decodeURIComponent(escape(atob(encodedString)));
    return decodedString;
}
var str = {'x':'aaaa'},
    enc = stringToUint(str),
    dec = uintToString(enc);

console.log(dec.x);

console.log(dec.x); 正在打印 `undefined。我做错了吗? 这是 jsfiddle http://jsfiddle.net/DQJyX/137/

为了使其正常工作,您需要在 stringToUint 函数中调用 JSON.stringify

function stringToUint(string) {
    var string = btoa(unescape(JSON.stringify(string))),
        charList = string.split(''),
        uintArray = [];
    for (var i = 0; i < charList.length; i++) {
        uintArray.push(charList[i].charCodeAt(0));
    }
    return new Uint8Array(uintArray);
}

function uintToString(uintArray) {
    var encodedString = String.fromCharCode.apply(null, uintArray),
        decodedString = decodeURIComponent(escape(atob(encodedString)));
    return decodedString;
}
var str = {'x':'aaaa'},
    enc = stringToUint(str),
    dec = uintToString(enc);

console.log(dec);

因为 stringToUint 需要一个字符串,并将对象传递给它会将 {'x':'aaaa'} 转换为 [Object object] 和 returns 表示该对象对象的数组,因此在调用 uintToString 时,数组被转换回 [Object object].

简单的解决方案是在将对象传递给函数之前对对象使用 JSON.stringify,然后使用 JSON.parse 转换为原始对象。

function stringToUint(string) {
    var string = btoa(unescape(encodeURIComponent(string))),
        charList = string.split(''),
        uintArray = [];
    for (var i = 0; i < charList.length; i++) {
        uintArray.push(charList[i].charCodeAt(0));
    }
    return new Uint8Array(uintArray);
}

function uintToString(uintArray) {
    var encodedString = String.fromCharCode.apply(null, uintArray),
        decodedString = decodeURIComponent(escape(atob(encodedString)));
    return decodedString;
}
var str = {'x':'aaaa'},
    enc = stringToUint(JSON.stringify(str)),
    dec = JSON.parse(uintToString(enc));
    
document.write(dec.x);

此代码 stringToUint 快了 40%,benchmark link

function stringToUint(string) {
  const str = btoa(unescape(encodeURIComponent(string)))
  const uintArray = []
  const len = str.length

  let i = -1

  while (++i < len) {
    uintArray[i] = str.charCodeAt(i)
  }

  return new Uint8Array(uintArray);
}