下面是一个示例代码,演示如何使用JavaScript在本地存储中编辑、清除和设置到期时间/日期:
// 设置本地存储
function setLocalStorage(key, value, expiresInMinutes) {
const expirationDate = new Date();
expirationDate.setMinutes(expirationDate.getMinutes() + expiresInMinutes);
const item = {
value: value,
expirationDate: expirationDate.getTime()
};
localStorage.setItem(key, JSON.stringify(item));
}
// 获取本地存储
function getLocalStorage(key) {
const item = JSON.parse(localStorage.getItem(key));
if (item && Date.now() < item.expirationDate) {
return item.value;
}
// 清除过期的本地存储
clearLocalStorage(key);
return null;
}
// 清除本地存储
function clearLocalStorage(key) {
localStorage.removeItem(key);
}
使用示例:
// 设置本地存储,有效期为5分钟
setLocalStorage('username', 'John Doe', 5);
// 获取本地存储
const username = getLocalStorage('username');
console.log(username); // 输出:John Doe
// 清除本地存储
clearLocalStorage('username');
// 再次获取本地存储
const usernameAfterClear = getLocalStorage('username');
console.log(usernameAfterClear); // 输出:null
以上代码演示了如何使用setLocalStorage
函数设置本地存储,并为其设置到期时间。getLocalStorage
函数用于获取本地存储的值,并检查其到期时间是否有效。如果存储项已过期,则会调用clearLocalStorage
函数清除存储项。