zhangxinxu / quiz

小测答题收集区
536 stars 43 forks source link

JS基础测试32 #26

Open zhangxinxu opened 5 years ago

zhangxinxu commented 5 years ago

本期都是些小题,每题数行代码:

大家提交回答的时候,注意缩进距离,起始位置从左边缘开始;另外,github自带代码高亮,所以请使用下面示意的格式。

```js
// 你的JS代码写在这里
 ```

其它:

  1. 首位答题者可获得额外2积分和直播翻牌机会;
  2. 本次答疑直播为5月26日(周日)上午10:00(不是周六,周六有事)
wingmeng commented 5 years ago

// 存储时加个时间戳 localStorage.setItem('userid', JSON.stringify({ data: 1, stamp: Date.now() + expires }));

// 取值时进行判断 var store_userid = JSON.parse(localStorage.getItem('userid')); var uidStamp = store_userid.stamp; var userid;

if (uidStamp <= Date.now()) { // 过期 localStorage.removeItem('userid'); } else { userid = store_userid.data; }

simplefeel commented 5 years ago

第1题

 document.cookie

第2题

 document.cookie = "userid=1"

第3题

let expireDate = new Date(time + 24*60*60*1000);
document.cookie="userid=1; expires="+expireDate.toUTCString();

第4题

function getCookie(name) {
    let cookieStr = document.cookie;
    let cookieList= cookieStr.split(";");
    for(let i=0;i<cookieList.length;i++){
        let coo = cookieList[i].split("=");
        if(coo[0].replace(/\s+/g,'') == name){
            return coo[1];
        }
    }
    return "";
}
getCookie('_csrfToken')

第5题

document.cookie="ywkey=; expires="+new Date(Date.now()-1000).toUTCString();

第6题

localStorage.setItem('userid', 1)

第7题

// timeout:单位分钟
function setStorage(key,value,timeout = 0){
    let _timeout = parseInt(timeout);
    localStorage.setItem(key, value);
    if (_timeout) {
        localStorage.setItem(`${key}__separator__`, Date.now() + 1000 * 60 * _timeout);
    } else {
        localStorage.removeItem(`${key}__separator__`);
    }
    return value;
}

function getStorage(key){
     const timeout = parseInt(localStorage.getItem(`${key}__separator__`) || 0);
     // 过期失效
     if (timeout) {
        if (Date.now() > timeout) {
            localStorage.removeItem(key);
            return;
        }
     }
     let value = localStorage.getItem(key);
     return value ? value : null;
}
setStorage('userid',1,7);
getStorage('userid')
Seasonley commented 5 years ago

// 1
document.cookie
//2
document.cookie ='userid=1'
//3
document.cookie ='userid=1; expires='+new Date(+new Date(time)+86400000).toUTCString()
document.cookie ='userid=1; max-age=86400'
//4
decodeURIComponent([document.cookie.match(/(?<=(^_|; _)csrfToken=)([^;]+)/g)].toString())
decodeURIComponent((/(^_|; _)csrfToken=([^;]+)/.test(document.cookie),RegExp.$2))
decodeURIComponent((document.cookie.match(/(^_|; _)csrfToken=([^;]+)/)||[,,''])[2])
//5
document.cookie="ywkey=;max-age=-1"
//6
localStorage.setItem('userid',1)
localStorage.userid=1
//7
var $Storage=new Proxy({},{
    set(obj,prop,val={value:null}){
        localStorage.setItem(prop,val&&val.value)
        val.expires!==undefined&&localStorage.setItem(prop+'__expires',Date.now()+val.expires)
    },
    get(obj,prop){
        var val={
            value:localStorage.getItem(prop),
            expires:localStorage.getItem(prop+'__expires'),
        };
        if(val.expires!==undefined&& val.expires < Date.now()){
            localStorage.removeItem(prop)
            localStorage.removeItem(prop+'__expires')
            return null
        }
        return val.value
    }
})
$Storage.userid={value:1,expires:86400000}
console.log($Storage.userid)//1
$Storage.userid={value:1,expires:-1}
console.log($Storage.userid)//null
//附赠批量获取cookie
var $cookie=Object.fromEntries(
    Array.from(
            document.cookie.matchAll(/([^=]+)=([^;]+)?;?\s?/g),
            item=>item.slice(1,3).map(decodeURIComponent)
        )
    );
var $cookie=JSON.parse('{'+
    document.cookie.replace(/([^=]+)=([^;]+)?(;)?\s?/g,
    (match,p1,p2,p3)=>decodeURIComponent(`"${p1}":"${p2}"${p3?',':''}`))
+'}')
NeilChen4698 commented 5 years ago

1.

document.cookie;

2.

document.cookie = 'userid=1';

3.

document.cookie = 'userid=1;expires=' + (new Date(time.getTime() + 3600000 * 24)).toGMTString();

4.

(document.cookie.split(';').find(v => v.split('=')[0] === '_csrfToken') || '').split('=')[1] || '';

5.

document.cookie = 'ywkey=;expires=' + (new Date(0)).toGMTString();

6.

localStorage.setItem('userid', 1);

7.

var myStorage = {
    get: function(key) {
        key = encodeURIComponent(key);
        var val = localStorage.getItem(key);
        if (val === null) {
            return null;
        }
        var valObj = val.split(';');
        var expireDate = valObj[1] || -1;
        if (expireDate != -1 && (new Date()).getTime() >= expireDate) {
            localStorage.removeItem(key);
            return null;
        } else {
            return decodeURIComponent(valObj[0]);
        }
    },
    set: function(key, val, expireDate) {
        expireDate = (expireDate instanceof Date) ? expireDate.getTime() : -1;
        localStorage.setItem(encodeURIComponent(key), encodeURIComponent(val) + ';' + expireDate);
    }
}
livetune commented 5 years ago

Demo

//1.
console.log(document.cookie)
//2.
document.cookie = 'userid=1;'
//3.
document.cookie =
  'userid=1;expires=' + new Date(+new Date() + 1000 * 60 * 60 * 24)
//4.
function getCookie(str) {
  return document.cookie.replace(
    new RegExp(`(?:(?:^|.*;\\s*)${str}\\s*\\=\\s*([^;]*).*$)|^.*$`),
    '$1',
  )
}
console.log(getCookie('_csrfToken'))
//5.
function removeCookie(str) {
  document.cookie = str + '=;expires=' + new Date(0)
}
document.cookie = 'ywkey=21'

removeCookie('ywkey')
// 6.
localStorage.setItem('userid', 1)
// 7.
function setLocalStorage(str, val, time) {
  localStorage.setItem(str, val + '-///-123111time=' + +new Date(time))
}
function getlocalStorage(str) {
  const data = localStorage.getItem(str)
  if (!data) {
    return data
  }
  const hasTime = data.indexOf('-///-123111time=')
  if (hasTime === -1) {
    return data
  } else {
    const res = data.substr(hasTime).split('=')[1]
    if (+new Date() > res) {
      localStorage.removeItem(str)
      return null
    } else {
      return data.substr(0, hasTime)
    }
  }
}
setLocalStorage('a', '22', +new Date() + 1000 * 4)
console.log('a', getlocalStorage('a'))
setTimeout(() => {
  console.log('a', getlocalStorage('a'))
}, 1000 * 5)
sghweb commented 5 years ago

第一题

document.cookie

第二题

document.cookie = "userid=1"

第三题

var exp = new Date(time);
exp.setTime(exp.getTime() + 24 * 60 * 60 * 1000); //过期时间 1天
document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString();

第四题

function getCookie(name) {
  var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)"); //正则匹配
  if (arr = document.cookie.match(reg)) {
    return unescape(arr[2]);
  } else {
    return "";
  }
}
getCookie("userid")

第五题

function delCookie(name) {
  var exp = new Date();
  exp.setTime(exp.getTime() - 1);
  var cval = getCookie(name);
  if (cval != null) {
    document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
  }
}
delCookie("userid")

第六题

localStorage.setItem('userid', 1)

第七题

function set(key, value) {
  var curTime = new Date().getTime();
  localStorage.setItem(key, JSON.stringify({
    data: value,
    time: curTime
  }));
}
function get(key, exp) {
  var data = localStorage.getItem(key);
  if (!data) {
    return false;
  }
  var dataObj = JSON.parse(data);
  if (new Date().getTime() - dataObj.time > exp) {
    return true;
  } else {
    return false;
  }
}
// 设置开始
set("userid", 1)
// 重新获取
if (get("userid", 2 * 60 * 1000)) {
  localStorage.removeItem("userid")
}
angentle commented 5 years ago
//1
document.cookie

//2
document.cookie = "userid=1"

//3
function setCookie (name, value, day,data=new Date()) {
  date.setTime(date.getTime() + 24 * 60 * 60 * 1000 * day)
  window.document.cookie = name + '=' + value + ';expires=' + date.toGMTString()
}
setCookie('userid',1,1,time)

//4
function getCookie (name) {
  if (document.cookie.length > 0) {
    let arr = document.cookie.split('; ')
    let value = ""
    arr.forEach(item=>{
        let str= item.split('=')
        if(str[0]===name){
            value = str[1]
        }
    })
    return value
  }
}
getCookie('_csrfToken')

//5
function delCookie(name) {
    setCookie(name,"",-1)
}

//6
localStorage.setItem('userid',1)

//7
Storage.prototype.setExpire=(key, value, expire) =>{
    let obj={
        data:value,
        time:Date.now(),
        expire:expire
    };
    localStorage.setItem(key,JSON.stringify(obj));
}

Storage.prototype.getExpire= key =>{
    let val =localStorage.getItem(key);
    if(!val){
        return val;
    }
    val =JSON.parse(val);
    let data = val.expire * 24 * 60 * 60 * 1000
    if(Date.now()-val.time > data){
        localStorage.removeItem(key);
    }
    return val.data;
}

localStorage.setExpire("userid",'1',7);
liyongleihf2006 commented 5 years ago

jsbin

//2.设置userId=1的cookie
setCookie("userId", 1)

//3.设置userId的过期时间为1天
setCookie("userId", 1, 24 * 60 * 60 * 1000)

//4.获取_csrfToken的值
const _csrfToken = getCookie("_csrfToken")
console.log(`_csrfToken=${_csrfToken}`)

//1.获取完整的cookie
const cookies = getCookies()
console.log(`cookies=${JSON.stringify(cookies)}`)

//5.删除ywkey的值
removeCookie('ywkey')

//6.用localStorage储存userId
localStorage.setItem("userId", 1)

//7.localStorage过期时间
// 重写localStorage,使得setItem可以传入第三个参数表示过期时间
// getItem的时候先删除过期时间的元素然后再返回对应键的值
// 因为localStorage还可以直接通过 .key 来获取其值,所以还单独写了一个clearExpires函数来清理所有的过期的元素
// 因为重写了localStorage,所以写了一个销毁重写localStorage的方法
rewriteLocalStorage()
localStorage.setItem("userId", 1, 24 * 60 * 60 * 1000)
console.log(`localStorage.getItem("userId")=${localStorage.getItem("userId")}`)
clearExpires()

/**
  * 获取整个cookie的json对象
  * @returns {object} cookies
  */
function getCookies() {
  const cookies = document.cookie
  if (!cookies) return {}
  return cookies.split(/;\s?/).reduce((cookies, current) => {
    const kv = current.split("=")
    cookies[kv[0]] = unescape(kv[1])
    return cookies
  }, {})
};
/**
  * 设置cookie
  * @param name cookie的名称
  * @param value cookie的值
  * @param millisecond cookie的过期时间
  */
function setCookie(name, value, millisecond) {
  if (millisecond) {
    const date = new Date(+Date.now() + millisecond)
    document.cookie = name + "=" + escape(value) + ";expires=" + date.toUTCString()
  } else {
    document.cookie = name + "=" + escape(value)
  }
};
/**
  * 获取对应名称的cookie
  * @param name cookie的名称
  * @returns {string} 不存在时,返回""
  */
function getCookie(name) {
  return getCookies()[name] || ""
};
/**
  * 删除cookie
  * @param name cookie的名称
  */
function removeCookie(name) {
  setCookie(name, '', -1)
}
/**
  * 重写localStorage
  */
function rewriteLocalStorage() {
  if (!window.__rewrite__localStorage) {
    Object.assign(window, {
      __rewrite__localStorage: true,
      __localStorage__setItem: localStorage.setItem,
      __localStorage__getItem: localStorage.getItem,
      __localStorage__removeItem: localStorage.removeItem
    })

    if (!localStorage.__expires) {
      localStorage.__expires = "{}"
    }

    localStorage.setItem = function (key, value, millisecond) {
      if (millisecond) {
        let __expires = JSON.parse(localStorage.__expires)
        __expires[key] = +Date.now() + millisecond
        localStorage.__expires = JSON.stringify(__expires)
      }
      window.__localStorage__setItem.call(this, key, value)
    }

    localStorage.getItem = function (key) {
      window.clearExpires()
      return window.__localStorage__getItem.call(this, key)
    }

    localStorage.removeItem = function (key) {
      let __expires = JSON.parse(localStorage.__expires)
      delete __expires[key]
      localStorage.__expires = JSON.stringify(__expires)
      return window.__localStorage__removeItem.call(this, key)
    }

    window.clearExpires = function () {
      let __expires = JSON.parse(localStorage.__expires)
      for (let key in __expires) {
        if (__expires[key] < Date.now()) {
          localStorage.removeItem(key)
        }
      }
    }
  }
}
/**
  * 销毁重写localStorage
  */
function destoryRewriteLocalStorage() {
  if (window.__rewrite__localStorage) {

    localStorage.setItem = window.__localStorage__setItem

    localStorage.getItem = window.__localStorage__getItem

    localStorage.removeItem = window.__localStorage__removeItem

    delete window.__rewrite__localStorage
    delete window.__localStorage__setItem
    delete window.__localStorage__getItem
    delete window.__localStorage__removeItem
    delete window.clearExpires
    localStorage.removeItem("__expires")
  }
}
ximuli commented 5 years ago
// 1
document.cookie

// 2
document.cookie = 'userid=1'

// 3
document.cookie = `userid=1;expires=${new Date(time + 24*60*60*1000).toUTCString()}`

// 4
getCookieValue('_csrfToken')

function getCookieValue(str) {
  let cookiesArr = document.cookie.split(/\s/)
  for (let i = 0; i < cookiesArr.length; i++) {
    let splitCookie = cookiesArr[i].split('=')
    if (splitCookie[0] === str) {
      return splitCookie[1]
    }
  }
  return ''
}

// 5
document.cookie = 'ywkey=;'

// 6
window.localStorage.setItem('userid', 1)

// 7
asyncguo commented 5 years ago
  1. 获取cookie
    document.cookie
  2. 新增cookie
    document.cookie = 'userid=1'
  3. 设置cookie过期时间
    time = new Date(time)
    time.setTime(time.getTime + (1 * 24 * 60 * 60 * 1000))
    document.cookie = `userid=1;expires=${time.toGMTString()}`
  4. 获取指定cookie
    function getCookie (key) {
    let cookieArr = document.cookie.split(';')
    for (let i = 0; i < cookieArr.length; i++) {
    let tempCookie = cookieArr[i].trim()
    if (tempCookie.startsWith(key)) {
      return  tempCookie.slice(key.length + 1)
    }
    }
    return ''
    }
    getCookie('_csrfToken')
  5. 删除cookie
    document.cookie = `ywkey='';expires=${new Date(0).toGMTString()}`
  6. 设置localStorage
    try {
    localStorage.setItem('userid', 1)
    } catch (e) {
    throw new Error(e)
    }                                      
  7. 设置localStorage过期时间及删除过期值
    /**
    * 设置localstorage
    * @param key 存储storage的名称 
    * @param val 存储storage的值
    */
    function setStorage (key, val) {
    try {
    let time = +new Date()
    localStorage.setItem(key, JSON.stringify({
      value: val,
      timer: time
    }))
    } catch (e) {
    throw new Error(e)
    }
    }
    /**
    * 获取localstorage
    * @param key 存储storage的名称 
    * @param expires 存储storage的时间
    */
    function getStorage (key, expires) {
    let vals = localStorage.getItem(key)
    if (vals) {
    let obj = JSON.parse(vals)
    let diffTime = +new Date() - obj.timer
    if (diffTime > expires) {
      localStorage.removeItem(key)
      throw new Error(`当前 ${key} 的存储已过期!`)
    } else {
      return obj.value
    }
    } else {
    throw new Error(`暂无 ${key} 的存储!`)
    }
    }
JaimeCheng commented 5 years ago

1. document.cookie;

2. setCookie('userId', 1);

3. setCookie('userId', 1, 24*60*60*1000);

4. getCookie('_csrfToken');

5. delCookie('ywkey');

6. localStorage.setItem('userid', 1);

7. 存储时同时加上时间戳,读取时判断下时间戳是否过期;

function setCookie(cookie_name, cookie_value, expiretime) {
    var exdate = new Date();
    exdate.setTime(Number(exdate) + expiretime);
    document.cookie = cookie_name + "=" + escape(cookie_value) + ((expiretime == null) ? "" : ";expires=" + exdate.toGMTString());
}

function getCookie(cookie_name) {
    if(document.cookie.length > 0) {
       cookie_start = document.cookie.indexOf(cookie_name + "=");//获取字符串的起点
       if(cookie_start != -1) {
          cookie_start = cookie_start + cookie_name.length + 1;//获取值的起点
          cookie_end = document.cookie.indexOf(";", cookie_start);//获取结尾处
          if(cookie_end == -1) cookie_end = document.cookie.length;//如果是最后一个,结尾就是cookie字符串的结尾
          return decodeURI(document.cookie.substring(cookie_start, cookie_end));//截取字符串返回
       }
     }
    return "";
}

function delCookie (cookie_name) {
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval = getCookie(cookie_name);
    if (cval != null)
    document.cookie = cookie_name + "=" + cval + ";expires=" + exp.toGMTString();
}
jsweber commented 5 years ago
document.cookie //第一题
document.cookie="userid=1" //第二题
//第三题
let time=+new Date();
document.cookie=`userid=1;expires=${new Date(time+24*60*60*1000).toUTCString()}`
//第四题
const getCsrfToken = () => {
    let key = '_csrfToken'
    let cookie = document.cookie
    let start = cookie.indexOf(key)

    if (start === -1) return ''
    return cookie.slice(start, cookie.indexOf(';', start)).split('=')[1]
}

//第五题
const delYwkey = () => {
    const key = 'ywkey'
    document.cookie = `${key}=0;expires=${new Date(Date.now()-100).toUTCString()}`
}

//第六题
localStorage.setItem('userId', 1)

//第七题
class MyStorage{
  constructor(){
    this.store = localStorage
  }

  static build(val, expires=1000 * 60 * 60 * 24){
    return {
      val,
      expires: Date.now() + expires
    }
  }

  setItem(key, val, expires){
    this.store.setItem(key, JSON.stringify(MyStorage.build(val, expires)))
  }

  getItem(key){
    let o = this.store.getItem(key)
    if(o) {
      o = JSON.parse(o)
      if (o.expires < Date.now()){
        this.store.removeItem(key)
        return null
      }
      return o.val
    }else {
      return o
    }
  }
}
let myStore = new MyStorage()
myStore.setItem('name', 'Lee', 1000 * 60)
myStore.getItem('name')
smileyby commented 5 years ago

使用document.cookie 设置或修改时,每次只能设置后修改一个cookie值

cookie值:以键值对的形式存在

每一个cookie都可以设置属性值:

  1. path:;path=path 如果没有定义,默认时当前文档的路径
  2. domain:;domain=domain 如果没有定义,默认为当前文档位置的路径的域名部分。如果指定了一个域,那么子域也包含在内
  3. max-age:;max-age=max-age-in-seconds 以秒为单位(例如一年为60*60*24*365)
  4. expires:;expires=date-in-GMTString-format如果没有定义,cookie会在对话结束时过期(取值格式参见Date.toUTCString
  5. secure:;secure cookie只通过https传输

cookie的值字符串可以用encodeURIComponent() 来保证它不包含任何逗号/分号或者空格(cookie值中禁止使用这些值)

以上内容来源Web-API-Document-cookie MDN

//=> overtimeDays => 过期的天数
var time = '2019-05-23 21:42:30';
function setCookie(key, value, overtimeDays, path, domain, secure) {
    var expiresString = new Date(new Date(time).getTime() + (60*60*24*1000*overtimeDays)).toUTCString();
    document.cookie = encodeURIComponent(key) + '=' + encodeURIComponent(value) + '; expires=' + expiresString + (domain ? '; domain=' + domain : '') + (path ? '; path=' + path : '') + (secure ? '; secure' : '');
}

function getCookie(key){
    var reg = RegExp('(| )'+ key +'=([^;]*)');
    var matchValue = document.cookie.match(reg);
    return matchValue ? matchValue[2] : '';
}

function delCookie(key, path, domain){
    var value = getCookie(key);
    if (value === '') {return false};
    document.cookie = encodeURIComponent(key) + '=' + encodeURIComponent(value) + '; expires=Thu, 01 Jan 1970 00:00:00 GMT' + (domain ? '; domain=' + domain : '') + (path ? '; path=' + path : '');
    return true;
}
//=> 1
document.cookie;

//=> 2
setCookie('userid', 1);

//=> 3
setCookie('userid', 1, 1);

//=> 4
getCookie('_csrfToken');

//=> 5
delCookie('ywkey');

//=> 6
localStorage.setItem('userid', 1);

//=> 7
//=> 实现清除的前提时,设置了过期时间,并且格式符合 new Date 能解析的格式 
localStorage.setItem('userid', '{"value": 1,"expires": "2019-05-23 22:27:00"}');
function checkEndLocalStorage(key){
    var data = localStorage.getItem(key)
    var expires = JSON.parse(data)['expires'];
    var now = new Date().getTime();
    var end = new Date(expires).getTime();
    if (now > end) {
        localStorage.removeItem(key);
    } else {
        setTimeout(function(){
            localStorage.removeItem(key);
        }, end - now);
    }
}
checkEndLocalStorage('userid');

疑问: cookie属性中的expiresmax-age的区别是什么?

// zxx: 兼容性吧 
frankyeyq commented 5 years ago
1. document.cookie
2. document.cookie="userid=1"
3. document.cookie=`userid=1;expire=${new Date(time + 24 * 60 * 60).toUTCString()}`
4. document.cookie.replace(/(?:(?:^|.*;\s*)_csrfToken\s*\=\s*([^;]*).*$)|^.*$/, "$1")
5. document.cookie = encodeURIComponent('ywkey') + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT";
6. localStorage.setItem('userid', 1)
7. 
function setLocalStorage(key, val, expireTime) {
        localStorage.setItem(key, JSON.stringify({val: val,expireTime: expireTime}));
}
function delExpired(key) {
    var isExpired = JSON.parse(localStorage.getItem(key)).expireTime - Date.now() < 0;
    if (isExpired) {
        localStorage.removeItem(key);
        return true;
    } else {
        return false;
    }
}
imlijq commented 5 years ago

1

    console.log(document.cookie);
    // language=zh-cn; __guid=157467068

2

    document.cookie="userid=1";
    console.log(document.cookie);
    // userid=1; language=zh-cn; __guid=157467068

3

    // obj:{
    //     key,
    //     value,
    //     hour,
    //     curTime,
    // }
    function writeCookie(obj) {
        var curTimeStamp = (obj.curTime ? new Date(obj.curTime) : new Date).getTime();
        var expiresStr = "";

        if (obj.hour != null) {
            expiresStr = new Date(curTimeStamp + 36e5 * obj.hour);
            expiresStr = "; expires=" + expiresStr.toUTCString();
        }

        document.cookie = obj.key + "=" + escape(obj.value) + expiresStr;
    }

    var time = new Date;
    writeCookie({
        key: "userid",
        value: "1",
        hour: 24,
        curTime: time,
    });
    console.log(document.cookie);    
    // userid=1; language=zh-cn; __guid=157467068

4

    function readCookie(key) {
        var value = "",
            preStr = key + "=",
            start = -1, end = -1;

        if (document.cookie.length > 0) {
            start = document.cookie.indexOf(preStr);
            if (start !== -1) {
                start += preStr.length;
                end = document.cookie.indexOf(";", start);
                if (end === -1) {
                    end = document.cookie.length;
                }
                value = unescape(document.cookie.substring(start, end));
            }
        }
        return value;
    }
    readCookie("_csrfToken"); // ''

5

    writeCookie({
        key: "ywkey",
        hour: 0,
    });

6

    localStorage.setItem("userid", "1");

7

    function setLocalStorage(keyStr, valueStr, hourNum) {
        var valueObj = {}
        if (hourNum != null) {
            valueObj = {
                value: valueStr,
                expireAt: (new Date).getTime() + 36e5 * hourNum,
            }
            localStorage.setItem(keyStr, JSON.stringify(valueObj));
            return;
        }
        localStorage.setItem(keyStr, valueStr);
    }

    function getLocalStorage(keyStr) {
        var result = localStorage.getItem(keyStr);
        var valueObj = {};

        if (result) {
            if (result.indexOf("expireAt") > -1) {
                valueObj = JSON.parse(result);
                if ((new Date).getTime() < valueObj.expireAt * 1) {
                    result = valueObj.value;
                }
                else {
                    localStorage.removeItem(keyStr);
                    result = null;
                }
            }
        }
        return result;
    }

    setLocalStorage("userid", "1", 2);
    getLocalStorage("userid");  
silverWolf818 commented 5 years ago

1.

document.cookie 
  1. document.cookie="userId=1";
  2. document.cookie = "userId=1;expires=" + new Date(time + 24*60*60*1000).toUTCString()
  3. function getCookie(key)
    {
        var name = key + "=";
        var str = document.cookie.split(';');
        for(var i=0; i<str.length; i++) {
            var item = str[i].trim();
            if (item.indexOf(name) === 0) return item.substring(name.length,item.length);
        }
        return "";
    }
    getCookie('_csrfToken');

    5

    document.cookie = "ywkey=;expires=" + new Date(0).toUTCString()
  4. localStorage.setItem('userId',1);
  5. function setKey(key,value){
        var obj = {
            data:value.data,
            time:new Date().getTime(),
            expire:value.expire
        };
        localStorage.setItem(key,JSON.stringify(obj));
    }
    
    function getKey(key){
        if(!localStorage.getItem(key)) return;
        var data = JSON.parse(localStorage.getItem(key));
        if(new Date().getTime() - data.time > data.expire){
            localStorage.removeItem(key);
            console.log('信息已过期');
        }else{
            return data;
        }
    }
    //data数据,expire过期时间毫秒值
    setKey('name',{ data:'tom',expire: 1000*60*60*24}); //过期时间24小时
    getKey('name')
XboxYan commented 5 years ago
//1.
document.cookie
//2
document.cookie = 'userid=1';
//3
document.cookie = 'userid=1;max-age='+60*60*24;//如果是本地时间可以直接用max-age
document.cookie = 'userid=1;expires='+new Date(+new Date(time)+60*60*24).toUTCString();
//4
function getCookies(name){
    var obj = {}
    document.cookie.replace(/\s?(\S+)=(\S+);/g,function($1,$2,$3){
        obj[$2] = $3;
    })
    return name?obj[name]||'':obj;
}
getCookie();//获取全部键值对
getCookie('_csrfToken');//获取指定键值
//5
document.cookie = "ywkey=;max-age=0";
//6
localStorage.setItem('userid',1);
//7
function setLocastorage(name,value,expires){
    localStorage.setItem(name, JSON.stringify({
        data: 1,
        expires: +new Date() + expires
    }));
}

function getLocastorage(name){
    var data = localStorage.getItem(name);
    if(!data){
        return null;
    }
    var isout =  JSON.parse(data).expires < +new Date();
    if(isout){
        localStorage.removeItem(name);
        return null;
    }else{
        return JSON.parse(data).data;
    }
}

setLocastorage('userid',1,60*60*24);
getLocastorage('userid');
Despair-lj commented 5 years ago
// 1
document.cookie
// 2
document.cookie = 'userid=1'
// 3
var nowTime = new Date(time)
document.cookie = 'userid=1;expires=' + new Date(nowTime.setDate(nowTime.getDate() + 1))
// 4 ;? 避免所取值是最后一个值没有分号的情况
var _csrfToken = ''
document.cookie.replace(/_csrfToken=(\S+);?/g, function(str, value) {
    _csrfToken = value
})
// 5
document.cookie = 'ywkey=;expires=' + new Date(0)
// 6
localStorage.setItem('userid', '1')
// 7
function setLocalStorage(key, value, time) {
  time = time ? new Date() + time : new Date().setDate(new Date().getDate() + 1)
  var val = {
    value: value,
    expires: time
  }
  localStorage.setItem(key, JSON.stringify(val))
}
function getLocalStorage(key) {
  var now = new Date()
  var val = JSON.parse(localStorage.getItem(key)) || {}
  if (val.expires && val.expires > now) {
    return val.value
  }
  localStorage.removeItem(key)
  return ''
}
setLocalStorage('userid', 1)
getLocalStorage('userid')
miaomiaolin commented 5 years ago

第一题

document.cookie

第二题

document.cookie = ‘userid=1’

第三题

document.cookie = 'userid=1; expires=' + new Date(time * 1000 + (24 * 60 * 60 * 1000)).toUTCString()

第四题

function getCookie(name) {  
  let arr = document.cookie.split(/;\s/)
  for (var i = 0;  i < arr.length;  i++) {
    var params = arr[i].split('=')
    if (name === params[0]) {
      return params[1]
    }
  }
  return ''
}
getCookie('_csrfToken')

第五题

document.cookie = 'ywkey=; expires=Thu, 01 Jan 1970 00:00:00 UTC '

第六题

localStorage.setItem('userid', 1)

第七题

const time = 24 * 60 * 60 * 1000 + Date.now() 
localStorage.setItem('userid', JSON.stringify({
  value: 1,
  expire: time 
}))

let expireDate = JSON.parse(localStorage.getItem('userid')).expire
if (expireDate <= Date.now()) {
  localStorage.removeItem('userid')
}
guqianfeng commented 5 years ago
    //第1题
    document.cookie
    //第2题
    document.cookie = `userid=1`;
    //第3题
    let expireDate = new Date(time + 24 * 60 * 60 * 1000);
    document.cookie = `userid=1; expires=${expireDate.toUTCString()}`;
    //第4题
    function getCookieVal(key){
        let cookieStr = document.cookie;
        let arr = cookieStr.split(";");
        for (let i = 0; i < arr.length; i++) {
            let kv = arr[i].split("=");
            if(key == kv[0]){
                return kv[1];
            }
        }
        return "";
    }
    getCookieVal("_csrfToken");
    //第5题
    function delCookie(key){
        document.cookie = `${key}='';expires=${new Date(0).toUTCString()}`;
    }
    delCookie("ywkey");
    //第6题
    localStorage.setItem('userid', 1);
    //第7题
    let days = 3; //过期时间设置
    let expires = days * 24 * 60 * 60 * 1000;
    localStorage.setItem("userid", JSON.stringify({
        val: 1,
        time: Date.now() + expires
    }));
    //过期删除
    if(JSON.parse(localStorage.getItem("userid")).time < Date.now()){
        localStorage.removeItem("userid");
    }
wind1996 commented 5 years ago
document.cookie

document.cookie='userid=1'

const expire=new Date(time+24*60*60*1000);

document.cookie='userid=1;expires'+expire.toUTCString()

decodeURIComponent([document.cookie.match(/;?(?<=_csrfToken=)([^;]+)/g)].toString())

localStorage.setItem('userid',1)
CandyQiu commented 5 years ago

默默的写了个demo, 预测自己5分~


// 1.如何获取文档完整的cookie? 
// 个人解读: 感觉对"完整"这个有疑问,参考下方文章: 不能读到的Cookie内容应该被设置成了 HttpOnly, 即客户端脚本无法读取,只能从服务端读取和操作。
// https://segmentfault.com/q/1010000009074595
document.cookie;

// 2.已知用户的userid=1,请新增Cookie值userid=1
document.cookie = "userid=1";

// 3.已知服务器返回的当前时间变量为time, 请设置上面的userid相关cookie过期时间为1天
// 学习参考:http://www.w3school.com.cn/js/js_cookies.asp
var time = new Date();
time.setTime(time.getTime() + (1*24*60*60*1000));
var expires = "expires="+ time.toUTCString();
document.cookie = "userid=1;" + expires + ";path=/";

// 4.获取名称是_csrfToken的Cookie值,没有返回空字符串
function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i <ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
         }
         if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
         }
     }
    return "";
} 
getCookie("_csrfToken");

// 5.删除名为 ywkey 的cookie值
// 直接把 expires 参数设置为过去的日期即可
document.cookie = "ywkey=;expires=Thu, 01 Jan 1970 00:00:00 GMT";

//6. cookie使用起来好麻烦,使用 localStorage 存储用户的userid=1
// localStorage学习参考
// https://www.runoob.com/jsref/prop-win-localstorage.html
localStorage.setItem("userid", 1);

//7.localStorage存储没有过期时间,请实现过期判断逻辑,如果过期,删除相关的localStorage的存储
// 思路:
// 存储时,增加日期e;;expires=。
// 读取时通过比较Date.parse(new Date())的大小,先判断是否过期,过期则删除

function setLocalStorage(key,value,time){
   time = (time&&Date.parse(time)) || Date.parse(new Date());
   localStorage.setItem(key, value + ";;expires="+time);
}

function isLocalStorageOverdue(key){
  var keyAndTime = localStorage.getItem(key) && localStorage.getItem(key).split(";;expires=") || "";
  if(keyAndTime[1] < Date.parse(new Date())){
     localStorage.removeItem(key);
  }
  return keyAndTime[0] || "";
}

setLocalStorage("key", "value", new Date().setTime(new Date().getTime() + (1*24*60*60*1000)));
isLocalStorageOverdue("key")

setLocalStorage("key2", "value2", new Date());
isLocalStorageOverdue("key2")
zhangxinxu commented 5 years ago

本期要点:

  1. 通过前端手段设置cookie的过期时间,一定要使用服务器时间,不能使用本地时间。两个原因:一个是和服务侧统一;本地时间是不准的,用户可以修改的;
  2. 获取cookie方法,一类:字符分隔,数组遍历,查询对应的键值。二类:正则,可以看看Seasonley的实现。
  3. ?<指的什么?--- (“(?<=\bsub)\w+\b”定位“sub”后面的字符串)。零宽断言。有兼容性问题,见下面讨论,不推荐实际项目使用。
  4. 设置过期时间可以expires,也可以是max-age。区别是什么呢?max-age是更新的过期时间用法,是IE9+浏览器才支持的,更容易理解和记忆。
  5. 删除cookie可以设置过期时间为之前。
  6. localStorage.setItem('userid', 1)或者简写:localStorage.userid = 1;
  7. localStorage过期时间,JSON.stringify和JSON.parse是可读性很不错,也容易维护的实现。
  8. 可以看下liyongleihf2006的localStorage重写,隐藏时间过期的细节,非常适合作为小工具,小组件。
Despair-lj commented 5 years ago
  1. ?<指的什么?---(“(?<= \ bsub)\ w + \ b”定位“sub”后面的字符串)。零宽断言。

经测试, 正则表达式零宽断言中的 ?<= 以及 ?<! 在 Firefox 和 Safari 浏览器中均无法正确运行,建议实际项目中不要使用这两种正则匹配语法

Seasonley commented 5 years ago
  1. ?<指的什么?---(“(?<= \ bsub)\ w + \ b”定位“sub”后面的字符串)。零宽断言。

经测试, 正则表达式零宽断言中的 ?<= 以及 ?<! 在 Firefox 和 Safari 浏览器中均无法正确运行,建议实际项目中不要使用这两种正则匹配语法

有道理,试试这个 decodeURIComponent((document.cookie.match(/(^_|; _)csrfToken=([^;]+)/)||[,,''])[2])

Despair-lj commented 5 years ago
  1. ?<指的什么?---(“(?<= \ bsub)\ w + \ b”定位“sub”后面的字符串)。零宽断言。

经测试, 正则表达式零宽断言中的 ?<= 以及 ?<! 在 Firefox 和 Safari 浏览器中均无法正确运行,建议实际项目中不要使用这两种正则匹配语法

有道理,试试这个 decodeURIComponent((document.cookie.match(/(^_|; _)csrfToken=([^;]+)/)||[,,''])[2])

这个方法确实不错,但是我觉得应该改为这样,因为 _csrfToken 是关键字, 把首字母分离出来不方便以后整合成函数使用

decodeURIComponent((document.cookie.match(/(^| )_csrfToken=([^;]+)/)||[,,''])[2])