简体   繁体   English

当天的尖叫 - Javascript以不同的方式序列化阵列

[英]Scream of the day - Javascript serialising arrays in different ways

This is royally annoying me at the moment: 这在当下令我很烦恼:

Consider an array of 2 values: 考虑一个包含2个值的数组:

var myArray = new Array();
myArray.push(21031);
myArray.push(21486);

When storing this in a cookie using jquery and toJSON, the value of the cookie looks like this: 使用jquery和toJSON将其存储在cookie中时,cookie的值如下所示:

["21031","21486"]

Now consider an array of a single value: 现在考虑一个单值的数组:

var myArray = new Array();
myArray.push(21239);

When storing this in a cookie using jquery and toJSON, the value of the cookie looks like this: 使用jquery和toJSON将其存储在cookie中时,cookie的值如下所示:

21239

This is almost completely useless to me as when I pull the items from the cookie, one comes back as a single value, the other comes back as an array that I can iterate over....ahhh! 这对我来说几乎完全没用,因为当我从cookie中提取项目时,一个回来作为单个值,另一个回来作为一个我可以迭代的数组....啊!

Why? 为什么?

I'd suggest using json2.js' JSON.stringify . 我建议使用json2.js'JSON.stringify It gets both of those cases right: 这两种情况都是正确的:

// [] is the same as new Array();
var foo = [];

foo.push(1);
foo.push(2);

JSON.stringify(foo); // "[1, 2]"

var bar = [];

bar.push(1);

JSON.stringify(bar); // "[1]"

In addition, when you use the json2.js API, your code automatically takes advantage of browser-native functionality in newer browsers. 此外,当您使用json2.js API时,您的代码会自动利用新浏览器中的浏览器本机功能。

You're doing something wrong. 你做错了什么。 Regardless of what JSON lib you're using (presuming it actually works), serializing this: 无论你使用什么JSON lib(假设它确实有效),序列化:

[21031, 21486]

should produce this: 应该产生这个:

"[21031,21486]"

Not ["21031","21486"] as you've posted. 你发布的不是["21031","21486"] That looks like you're serializing the individual elements. 这看起来像是在序列化各个元素。 Post more code. 发布更多代码。

Cookies are strings, so all you are doing is storing a string serialisation of the array. Cookies是字符串,所以你要做的就是存储数组的字符串序列化。 If I do: 如果我做:

document.cookie = [1, 2].toString()

then document.cookie has the value "1,2", which is not an array. 然后document.cookie的值为“1,2”,这不是一个数组。

EDIT: as toJSON isn't a native jQuery method, it presumably comes from a plugin. 编辑:因为toJSON不是一个原生的jQuery方法,它可能来自一个插件。 Have you checked the plugin documentation? 你检查过插件文档了吗? Alternatively, try a different plugin that works as you expect. 或者,尝试使用其他预期的插件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM