将JS对象数组存储在cookie中,没有插件?

sim*_*mon 2 javascript cookies

什么是存储它的最佳方式:

var mydata = [{'11 Alveston Road, Manchester':1},
              {'12 Plymouth Street, Liverpool':2}];
Run Code Online (Sandbox Code Playgroud)

在cookie中以后检索?

我显然可以简单地将它全部转换为文本字符串,并添加一些符号作为分隔符(希望这些符号不会出现在数据值的任何位置),但它似乎有点hacky!

如果可能的话,我也想避免使用jQuery cookie插件等 - 我正在使用移动设备,而且每个额外的文件调用都会受到影响.

谢谢!

lon*_*day 5

这听起来像是一份工作JSON.stringify:

var myData = JSON.stringify(
    [
        {'11 Alveston Road, Manchester':1},
        {'12 Plymouth Street, Liverpool':2}
    ]
); // "[{"11 Alveston Road, Manchester":1},{"12 Plymouth Street, Liverpool":2}]"
Run Code Online (Sandbox Code Playgroud)

该数组将转换为JSON格式的字符串,然后您可以将其用作cookie的值.你可以解码它JSON.parse.


注意:由于您使用的是移动浏览器,因此它们可能非常现代,因此本机安装了JSON.在这些情况下,您可以使用此库来解决此问题.