Local storage: cookie, localStorage, sessionStorage.

Local storage: cookie, localStorage, sessionStorage.

cookie: an attribute under the document object.

  • The type is " small text file ", which is the data (usually encrypted) stored on the user's local terminal by some websites in order to identify the user's identity and perform Session (session control) tracking. The information is temporarily or permanently saved by the user's client computer. .
let cookie = {
    
    
	// 写入/修改cookie
	set(key,value,expires){
    
    
		let d = new Date(expires);
		document.cookie = key + "=" + value + ";expires="+d;
	},
	// 读取cookie
	get(key){
    
    
		let arr = document.cookie.split("; ")
		var result = {
    
    }
		arr.forEach(item=>{
    
    
			let key = item.split("=")[0];
			let value = item.split("=")[1];
			result[key]=value;
		})
		return key?result[key]:result;
	},
	// 删除cookie
	remove(key){
    
    
		if(this.get(key)){
    
    
			document.cookie = key + "=18;expires=" + new Date('1999-09-09');
			return true;
		}
		else{
    
    
			return false;
		}
	}
}

localStorage: It is used to save the data of the entire website for a long time. The saved data has no expiration time until it is manually deleted.

* setItem(key,value) 写入
* getItem(key) 获取
* removeItem(key) 删除
* clear() 清空
* .length 返回有几条数据

sessionStorage: Used to temporarily save the data of the same window (or tab), which will be deleted after closing the window or tab.

* setItem(key,value) 写入
* getItem(key) 获取
* removeItem(key) 删除
* clear() 清空
* .length 返回有几条数据

The difference between cookie, localStorage and sessionStorage.

* cookie写法麻烦,兼容性好,可灵活设置生命周期。
* localStorage相对于cookie来说写法简单,兼容性一般,是永久性存储并不可设置过期时间。
* sessionStorage相对于localStorage来说只有生命周期不一样,sessionStorage的生命周期是会话(存活与当前标签页中)。

Guess you like

Origin blog.csdn.net/yanyuyanyan/article/details/112472661