Open wingmeng opened 5 years ago
良好
优秀、良好、一般、差劲
localStorage polyfill (使用 cookie 模拟)
!window.localStorage && !function(win) {
var thousandYears = 1e3 * 365 * 24 * 36e5;
function getCookies() {
return document.cookie.match(/([^;=]+)=([^;]+)/g) || [];
}
function getExpires(flag) {
flag = flag || 1;
return 'expires=' +
(new Date((+new Date()) + thousandYears * flag)).toUTCString();
}
function get(key) {
var cookies = getCookies();
for (var i = 0; i < cookies.length; i++) {
var param = cookies[i].match(/^\s*([^=]+)=(.+)/);
if (param[1] === String(key)) {
return decodeURIComponent(param[2]);
}
}
return null;
}
function set(key, value, isExpired) {
document.cookie = [
key + '=' + encodeURIComponent(value),
getExpires(isExpired ? -1 : 1),
'path=/'
].join('; ');
}
function remove(key) {
set(key, '', true);
}
function clear() {
var cookies = getCookies();
for (var i = 0; i < cookies.length; i++) {
var key = cookies[i].match(/^\s*([^=]+)/)[1];
remove(key);
}
}
// 注册到 window 对象上
win.localStorage = {
getItem: get,
setItem: set,
removeItem: remove,
clear: clear
};
}(window);
题目:
我的回答:
第 1 题:
document.cookie
第 2 题:
document.cookie = 'userid=1';
第 3 题:
第 4 题:
第 5 题:
第 6 题:
localStorage.setItem('userid', 1);
第 7 题:
// 存储时加个时间戳 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; }