JavaScript常用工具方法(7)Storage 储存操作

7. Storage 储存操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
class StorageFn {
constructor () {
this.ls = window.localStorage;
this.ss = window.sessionStorage;
}

/*-----------------cookie---------------------*/
/*设置cookie*/
setCookie (name, value, day) {
var setting = arguments[0];
if (Object.prototype.toString.call(setting).slice(8, -1) === 'Object'){
for (var i in setting) {
var oDate = new Date();
oDate.setDate(oDate.getDate() + day);
document.cookie = i + '=' + setting[i] + ';expires=' + oDate;
}
}else{
var oDate = new Date();
oDate.setDate(oDate.getDate() + day);
document.cookie = name + '=' + value + ';expires=' + oDate;
}

}

/*获取cookie*/
getCookie (name) {
var arr = document.cookie.split('; ');
for (var i = 0; i < arr.length; i++) {
var arr2 = arr[i].split('=');
if (arr2[0] == name) {
return arr2[1];
}
}
return '';
}

/*删除cookie*/
removeCookie (name) {
this.setCookie(name, 1, -1);
}

/*-----------------localStorage---------------------*/
/*设置localStorage*/
setLocal(key, val) {
var setting = arguments[0];
if (Object.prototype.toString.call(setting).slice(8, -1) === 'Object'){
for(var i in setting){
this.ls.setItem(i, JSON.stringify(setting[i]))
}
}else{
this.ls.setItem(key, JSON.stringify(val))
}

}

/*获取localStorage*/
getLocal(key) {
if (key) return JSON.parse(this.ls.getItem(key))
return null;

}

/*移除localStorage*/
removeLocal(key) {
this.ls.removeItem(key)
}

/*移除所有localStorage*/
clearLocal() {
this.ls.clear()
}

/*-----------------sessionStorage---------------------*/
/*设置sessionStorage*/
setSession(key, val) {
var setting = arguments[0];
if (Object.prototype.toString.call(setting).slice(8, -1) === 'Object'){
for(var i in setting){
this.ss.setItem(i, JSON.stringify(setting[i]))
}
}else{
this.ss.setItem(key, JSON.stringify(val))
}

}

/*获取sessionStorage*/
getSession(key) {
if (key) return JSON.parse(this.ss.getItem(key))
return null;

}

/*移除sessionStorage*/
removeSession(key) {
this.ss.removeItem(key)
}

/*移除所有sessionStorage*/
clearSession() {
this.ss.clear()
}

}