sessionStorage,关闭窗口就被清除;
localStorage,一直存在直到手动删除;
cookie,设置有效期,可以直接实现标题的需求
今天不想多说话,直接贴上代码:
//判断是否支持 比如浏览器开启了隐私模式var isCookie = () = >{ return navigator.cookieEnabled}//存储function setCookie(cname, cvalue, exdays = 0) { cvalue = encodeURIComponent(JSON.stringify(cvalue)) if (exdays >0) {var d = new Date().getTime() + exdays * 24 * 3600 * 1000 + 8 * 3600 * 1000 var expires = "expires=" + new Date(d).toUTCString() document.cookie = cname + "=" + cvalue + "" + expires + "path=/" } else {document.cookie = cname + "=" + cvalue + "" + "path=/" }}//获取function getCookie(cname) { var name = cname + "=" var ca = document.cookie.split("") for (var i = 0i <ca.lengthi++) {var c = ca[i] while (c.charAt(0) == " ") { c = c.substring(1) }if (c.indexOf(name) == 0) { let d = c.substring(name.length, c.length) return JSON.parse(decodeURIComponent(d)) } } return ""}//获取 通过正则// function getCookie(name) {// var arr,// reg = new RegExp("(^| )" + name + "=([^]*)(|$)")// if ((arr = document.cookie.match(reg))) {// return JSON.parse(decodeURIComponent(arr[2]))// } else {// return null// }// }//删除function deleteCookie(name) { var date = new Date() date.setTime(date.getTime() - 1) var delValue = getCookie(name) if (delValue) {document.cookie = name + "=" + delValue + "expires=" + date.toGMTString() }}
使用示例:
//定义keyconst tk = "tk2020"const uk = "uk2020"//保存setCookie(tk, "14332239527007001", 0)setCookie(uk, { id: 1, name: "以气御码" }, 0)//获取let token = getCookie(tk)let user = getCookie(uk)console.log(token)console.log(user)
当使用setCookie时,传0或不传,表示关闭浏览器后就被清除,截图预览:
当登录的信息存储为这种形式,可以实现关闭浏览器,就清除登录信息。也可以再配合登录有效期,总不能“只要不关浏览器,就不退出登录了”。
文档:
MDN Cookie(https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie)W3c Cookie(https://www.w3school.com.cn/js/js_cookies.asp)菜鸟教程 Cookie(https://www.runoob.com/js/js-cookies.html)
最笨的方法是用对象的键值对做标记,如:
var arr=[1,2,3,4,5,6,4]function check(data){//data一定是数组
if(!data) data=[]
return data
if(data.length==0) return data
var _obj={}//用于标记
var newArr=[]//删除重复后的数组
for(var i=0i<data.lengthi++){
var val=data[i]
if(obj[val]||obj[val]==0){//已结存在,注意值为0时if(0){}的判断--永远为false
continue
}else{
obj[val]=val//把val以键值对的形式存入obj
newArr.push(val)
}
}
return newArr//返回删除重复的数组
}
var arr1=check(arr)//结果为:[1,2,3,4,5,6]