JavaScript Tip of the Week for November 25, 1996: Everything You Ever Wanted to Know About Cookies | 3 | WebReference

JavaScript Tip of the Week for November 25, 1996: Everything You Ever Wanted to Know About Cookies | 3

JavaScript Tip of the Weekfor November 25, 1996: Everything You Ever Wanted to Know About Cookies

If you plan on using a lot of Cookies on your site, it is preferable to store them in an array, as opposed to storing them using lots of different names. All you need it two basic functions to set and get Cookie arrays (along with the set/get Cookie code). First, to create a Cookie array, use this function:
    function setCookieArray(name){
    this.length = setCookieArray.arguments.length - 1;
        for (var i = 0; i 
It creates an array of Cookies in the Cookie file, not in memory. There is no way to actually store an array in the Cookie file, but this tricks the Cookies into thinking they are arrays. To create a Cookie array using this function, specifiy the expiration date, name of the Cookie array, and the data to go into the Cookie:
    var expdate = new Date();
    expdate.setTime (expdate.getTime() +  (24 * 60 * 60 * 1000 * 365)); 
    var testArray = new setCookieArray(
    "_jtotw", <-- name of the Cookie array
    "my",     <-- data for first element of Cookie array
    "data",   <-- data for second element, etc.
    "is",
    "very",
    "important");
The above Cookie array was assigned the name "_jtotw" and was given (as data) 5 words. To get data from a Cookie array, use this function which scans through the Cookie file looking for the specified array and putting it in memory:
    function getCookieArray(name){
    var i = 0;
        while (getCookie(name + i) != null) {
        this[i + 1] = getCookie(name + i);
        i++; this.length = i; 
        }
    }
To access the data that is stored in the "_jtotw" Cookie array, simply make one call to getCookieArray():
    var testArray = new getCookieArray("_jtotw");
After loading the "_jtotw" Cookie array using getCookieArray(), treat the array like you would any other array (but starting at 1, not 0). To print out the first element, or piece of data, in the array, use this:
    document.write (testArray[1]);
The above code would display "my". Grabbing testArray[2] would display "data", etc.

Source