How to use a cookie as Javascript Array?

2

Doubt: I would like to know a way to use Cookie , as if it were a Array .

Problem: I can not figure out how to do this.

Example: Suppose I have a Array called Foo which would be as follows:

var Foo = ["qualquer coisa, que esteja|escrito-simbolos*e_outros","qualquer coisa, que esteja|escrito-simbolos*e_outros"];

And I would like to store this information in a Cookie named FooArray , and then I could redeem the value of Cookie and use it as a Array .

How could it be done?

    
asked by anonymous 03.02.2014 / 14:34

3 answers

3

A reliable way would be to transform the array to a String in JSON format:

var Foo = [1,2];
var FooStr  = JSON.stringify(Foo);
var OtherFoo = JSON.parse(FooStr)

The only drawback of this approach to join / split is that it will take some extra characters for the JSON representation. So, for arrays of numbers for example, @Carlos's answer could save a few bytes.

And to work with cookies I suggest using the jQuery.cookie plugin. To Store:

var Foo = [1,2];
$.cookie('FooCookie', JSON.stringify(Foo));

And to recover:

var OtherFoo = JSON.parse($.cookie('FooCookie'));
    
03.02.2014 / 14:49
2

A good practice is to use JSON .

You can convert your object to string with:

JSON.stringify(Foo); 

Before writing the cookie and then retrieving with:

Foo = JSON.parse(strCookie);
    
03.02.2014 / 14:48
1

Use the methods join and split :

var Foo = [1,2];
var cookieData = Foo.join(',');
Foo = cookieData.split(',');
    
03.02.2014 / 14:41