---
title: "Javascript中关于Cookie存储Array集合"
author: "jaw111"
date: "2011-12-20T15:36:42Z"
tags: []
categories: ["Web前端"]
slug: "javascript-cookie-array"
draft: false
lastmod: "2011-12-20T15:37:00Z"
id: 1317773
url: "https://caryjava.iteye.com/blog/1317773"
---

因为Cookie中不能直接存储Array集合，只能存储Javascript基本数据类型。所以我这边采用把Array集合转换成JSON对象进行存储就可以实现。同理处理Object对象也是一样。

 

function addHistory(\_hcObj){

var \_hclx = \_hcObj.hclx;

var array = JSON.decode(getCookie("HISTORY"+\_hclx));//Cookie中存放的数组通过解码方式还原

 

if(array != null && array.length &gt; 0){

while(true){

if(array.length &gt;= 5){

array.splice(0,1);//剔除array数组中第一个对象。数组中只保留不超过5个对象

}else{

break;

}

}

array.push(\_hcObj);//array数组中填充对象

setCookie("HISTORY"+\_hclx,JSON.encode(array),1);//array 数组通过编码之后，存放在Cookie中

}else{

array = new Array();

array.push(\_hcObj);

setCookie("HISTORY"+\_hclx,JSON.encode(array),1);

}

}

下面提供一个通过的JS文件下载。