Home >Web Front-end >JS Tutorial >JavaScript code to save array to cookie_javascript skills
Arrays in JavaScript cannot be directly saved as cookies (PHP can). Then the array must be transferred to a string and then saved in a cookie. For a simple one-dimensional array, we can directly use toString() or join:
The toString function method in JavaScript returns the string representation of the object.
Usage: objectname.toString([radix])
Where objectname is a required option. To get the object represented by a string.
radix is optional. Specifies the base when converting numeric values to strings.
Join is one of the methods.
Format: objArray.join(seperator)
Purpose: Use the character specified by seperator as the separator to convert the array into a string. When seperator is a comma, its function is the same as toString().
If it is a multi-dimensional array, we have to use JSON.
JSON (JavaScript Object Notation) is a lightweight data exchange format. Easy for humans to read and write. It is also easy for machines to parse and generate. It is based on a subset of JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999. JSON uses a completely language-independent text format, but also uses conventions similar to the C language family (including C, C, C#, Java, JavaScript, Perl, Python, etc.). These properties make JSON an ideal data exchange language.
Here we use the PHP2JS function library to implement it, which requires the two functions json_decode and json_encode. Friends who know PHP can understand the meaning of these two functions. json_decode is JSON to array, json_encode is array to JSON.
It should be noted that JavaScript will filter some characters when saving cookies, such as: "{" is filtered into "{_", etc. Therefore, these characters must be filtered when obtaining cookies, otherwise json_decode will cause an error.
The following is a simple example: