You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为购物车中添加的每个商品设置24小时过期自动移除功能

实现购物车商品24小时自动移除功能

需求:为购物车中每个商品设置24小时时间限制,到期后自动将该商品从购物车中移除。

以下是具体的JavaScript实现代码:

const isExpired = (timestamp) => {
    const now = new Date().getTime();
    const oneDay = 24 * 60 * 60 * 1000;
    return now - timestamp > oneDay;
};
 
const removeExpiredItems = () => {  
    for (let productId in cart) {
        if (isExpired(cart[productId].addedAt)) {
            delete cart[productId];
        }
    }
};

代码说明

  • isExpired 函数:接收商品添加时的时间戳,计算当前时间与该时间戳的差值,若差值超过24小时对应的毫秒数(86400000),则返回true表示商品已过期。
  • removeExpiredItems 函数:遍历购物车对象的所有商品ID,对每个商品调用isExpired函数判断是否过期,若过期则通过delete操作从购物车中移除该商品。

内容的提问来源于stack exchange,提问作者Francis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 05:33:11