jQuery数组放入cookie [英] jQuery arrays into cookie

查看:108
本文介绍了jQuery数组放入cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var adddata = [];
adddata[ group ] = [];
adddata[ group ][ id ] = option; // option is an object like { foo : 'bar' }

console.log( adddata ); // looks ok

$.cookie( 'cookiename', JSON.stringify( adddata ) );
console.log( $.cookie( 'cookiename' ) ); // just "[]"
$.cookie( 'cookiename', adddata );
console.log( $.cookie( 'cookiename' ) ); // "an empty string"

// in another file
var cdata = JSON.parse( $.cookie( 'cookiename' ) );
$.each( cdata, function( group, items ){
    /* and so on */
});

如您所见,我使用$ .cookie插件.但是,如何才能以正确的方式将数组存储到Cookie中?

As you can see, I use the $.cookie plugin. But how can I store arrays into the cookie the right way?

感谢&问候, 亚历克斯

Thanks & regards, Alex

推荐答案

如果groupid不是数字值,则JSON.stringify将忽略它们.将数组转换为JSON时,仅考虑数字属性.

If group and id are not numeric values, JSON.stringify will ignore them. Only numeric properties are taken into account when converting an array to JSON.

请参阅:

> a = []
  []
> a['foo'] = 5
  5
> a[0] = 42
  42
> JSON.stringify(a)
  "[42]"

如果要处理非数值属性,则必须使用对象 {}:

You have to use an object {} if you deal with non-numerical properties:

> a = {}
  Object
> a['foo'] = 5
  5
> JSON.stringify(a)
  "{"foo":5}"

请勿将JavaScript 数组用作关联数组. JS数组应仅具有数字键.对于其他所有内容,请使用普通对象.

Never use a JavaScript array as associative array. JS arrays should only have numerical keys. For everything else, use plain objects.

这篇关于jQuery数组放入cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆