localStorage.setItem
方法用于将值保存到指定的键。但是 localStorage
并没有提供直接设置过期时间的方法。你可以通过以下方式模拟过期时间:
-
使用当前时间戳加上过期时间(以毫秒为单位)来设置过期时间戳。
-
每次获取数据时检查这个时间戳是否超过当前时间。
以下是一个简单的示例,展示如
// 设置一个项,有效期为1小时
const expirationTime = 1 * 60 * 60 * 1000; // 1小时后过期
const now = new Date().getTime();
const itemExpiration = now + expirationTime;
// 将时间戳作为字符串存储
localStorage.setItem('item', JSON.stringify({
value: 'your_value',
expiration: itemExpiration
}));
// 获取项时检查是否过期
function getItemWithExpirationCheck(key) {
const item = JSON.parse(localStorage.getItem(key));
const now = new Date().getTime();
if (item && item.expiration > now) {
return item.value;
} else {
// 如果过期,可以删除该项或者返回null/undefined
localStorage.removeItem(key);
return null;
}
}
// 使用函数获取项
const value = getItemWithExpirationCheck('item');
console.log(value); // 如果未过期,打印 'your_value';如果过期,打印 null
何设置一个具有过期时间的项: