JS比较两个Date日期显示对应图标时if判断始终失效如何解决
问题根因
- Date属于引用类型,直接用
===比较的是两个对象的内存地址而非日期值,即使两个日期的时间戳完全一致,===判断也会返回false getDay()是获取当前星期(返回值0-6对应周日到周六),要获取当月的日期需要调用getDate()方法new Date(year, monthIndex, day)的月份参数是从0开始计数的,你已经给月份做了+1处理,传入构造函数后会比实际月份多1个月- 模板嵌套逻辑错误,
currentIcon的判断模板嵌套在pastIcon的判断分支内,即使currentIcon为true,也需要pastIcon同时为true才会生效,不符合互斥的业务逻辑
修复代码
JS逻辑部分
connectedCallback() { const today = new Date(); // 构造当天0点的日期对象,避免时分秒干扰判断 const currentDate = new Date(today.getFullYear(), today.getMonth(), today.getDate()); // 构造目标日期0点的对象,月份参数传9对应10月 const targetDate = new Date(2021, 9, 5); // 比较时间戳判断日期是否相等 if (currentDate.getTime() === targetDate.getTime()) { this.currentIcon = true; this.pastIcon = false; } else { this.currentIcon = false; this.pastIcon = true; } }
模板部分
<template> <template if:true={pastIcon}> <lightning-dynamic-icon type="trend" option="down" alternative-text="Trending down"> </lightning-dynamic-icon> </template> <template if:true={currentIcon}> <lightning-dynamic-icon type="trend" option="up" alternative-text="Trending up"> </lightning-dynamic-icon> </template> </template>
补充说明
日期比较也可以直接用+操作符转换为时间戳简写:+currentDate === +targetDate,效果和getTime()完全一致。
内容的提问来源于stack exchange,提问作者malik ambar
相关产品推荐
相关产品推荐

