一:区别
1、cookie:(4kb)
可以设置到期时间、在任意浏览器的窗口都可以访问到
document.cookie = 'name="zs"; max-age=1'; // 设置变量和到期时间
console.log(document.cookie) // 获取cookie的值
document.cookie = 'name=zs; max-age = -1' // 删除当前cookie值
cookie方法的封装
let manageCookie = {
set (key, value, time) {
document.cookie = `${key}=${value}; max-age=${time}`
return this;
},
get (key, cb) {
let cookie = document.cookie,
cookieArr = cookie.split('; '),
itemArr = null;
cookieArr.forEach(function (cookieItem) {
itemArr = cookieItem.split('=');
// 如果键名相同
if(itemArr[0] === key) {
cb(itemArr[1]);
} else {
cb();
}
})
return this;
},
delete (key) {
this.set(key, '', -1);
return this;
}
}
2、localStorage(10MB)
永久存储、除非手动删除、在任意浏览器的窗口都可以访问到
window.localstorage.getItem(key);
window.localstorage.setItem(key, value);
window.localStorage.removeItem(key, value)
3、sessionStorage(5MB)
只有在当前页面才能访问得到;
window.sessionStorage.getItem(key);
window.sessionStorage.setItem(key, value);
window.sessionStorage.removeItem(key, value)