首先說一下我寫這篇文章的初衷鼓择,最近有用到cookie的一些相關操作,但是檢索了很多網上的文章大多數(shù)都是存取單個數(shù)據(jù)的cookie封裝鸭巴,cookie存取數(shù)組的文章很少伏蚊,為了方便后邊的同學減少開發(fā)中浪費過多時間馅巷,所以借鑒一些文章和自己的代碼加工編寫了此文膛虫。
數(shù)組去重
const unique = (arr) => {
// 遍歷arr,把元素分別放入tmp數(shù)組(不存在才放)
var tmp = new Array();
for(var i in arr){
//該元素在tmp內部不存在才允許追加
if(tmp.indexOf(arr[i])===-1){
tmp.push(arr[i]);
}
}
return tmp;
}
存cookie
const setCookie = (name,value,day) => {
const date = new Date();//用來設置過期時間用的钓猬,獲取當前時間加上傳進來的iDay就是過期時間
date.setDate(date.getDate() + day);
const cookieObj = [];
if(getCookie(name) !== null){
if(getCookie(name).split(',').length >= 1) {
for(let i = 0;i < getCookie(name).split(',').length;i++){
cookieObj.push(getCookie(name).split(',')[i]);
}
}else{
cookieObj.push(getCookie(name).split(','));
}
}
cookieObj.push(value);
let arr = unique(cookieObj);//數(shù)組去重
document.cookie = name + '=' + arr + ';expires=' + date;
}
取cookie
const getCookie = (name) => {
if (document.cookie.length>0){
let start = document.cookie.indexOf(name + "=")
if (start != -1){
start = start + name.length + 1;
let end = document.cookie.indexOf(";",start);
if (end == -1) end = document.cookie.length
return unescape(document.cookie.substring(start,end))
}
}
return null;
}
刪除cookie
(一般用不到稍刀,存儲cookie的時候可以傳入失效時間)
const removeCookie = (name) =>{
setCookie(name, 1, -1); //-1就是告訴瀏覽器數(shù)據(jù)已經過期,瀏覽器就會立刻去刪除cookie
};
用法
// 存儲cookie,有效期521天;
setCookie('haha',value,521);//'haha'是cookie的名敞曹,value就是你要存的具體數(shù)據(jù)账月,521就是設置的保存時間
const haha = getCookie('haha');/
if(haha === null) {
$scope.haha = '';
}else{
const arrHaha = haha.split(',');
}
此時html就可以渲染arrHaha
這條cookie數(shù)據(jù);
至此,關于cookie的一系列流程操作就介紹到這里异雁,希望對你有所幫助捶障!