在ArrayBuffer中存储一个json对象

时间:2016-03-13 14:39:29

标签: javascript 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/

3 个答案:

答案 0 :(得分:4)

因为stringToUint需要一个字符串,并且将一个对象传递给它会将{'x':'aaaa'}转换为[Object object]并返回一个表示该对象对象的数组,因此调用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);

答案 1 :(得分:0)

要在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);

答案 2 :(得分:0)

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);
}