- == (双等) 指的是宽松相等 — 会做隐式类型转换
-
- 举例:
0 == '' // true
'5' == 5 // true
- 举例:
- ===(三等) 指的是严格相等 — 类型和值都相等才 true
-
- 举例:
0 === '' // false
'5' === 5 // false
- 举例:
在业务逻辑里经常因为隐式转换导致条件误判,业界普遍推荐 一律用 === / !==。
举例场景:判断用户是否从第 0 张滑块回到最后一张
① 错误版本 (用了 ==)
onChange(e) {
const current = e.detail.current; // 数字 0、1、2…
const source = e.detail.source; // 'touch' | 'autoplay'
const pageCount = this.data.slides.length; // 假设 = 5
// ❌ BUG:尝试判定「是手动触发 & current == 0」
if (source == 'touch' && current == 0) { // ← 坑点
tt.showToast({ title: 'You are back to first page!' });
}
}
source 是 字符串 ‘touch’,判断没问题;
current 是 数字 0 ,但是==是宽松相等。
- 存在的问题:current 正常是数字 0,但若某次回调把它写成字符串 ‘00’、空字符 ’ '、或者 false,右侧是number类型,== 会把字符串’00’ 转成数字 0,再做比较:
-
- 导致current 是
'00'
' '
和false的时候,current == 0的实际结果都是True!
- 导致current 是
- 于是会把本不该弹的情况当成当前页=0,误弹提示。
② 正确版本 (统一类型 + 用 ===)
onChange(e) {
const { current, source } = e.detail;
const isTouchFirst = (source === 'touch' && current === 0);
if (isTouchFirst) {
tt.showToast({ title: 'You are back to first page!' });
}
}
改用 ===,同时把常量也写成数字 0;
现在只有 “手动”+“current 为数字 0” 才会满足条件;
自动播放到第 0 页 (source === ‘autoplay’) 不会再误判。
★ 结论
用 === / !==:让类型不符合时立即为 false,更早暴露错误;
常量写成正确类型:数字用 0,字符串用 ‘0’,别混;
小程序事件对象字段(detail.current、detail.source…)要先确认 准确类型,再写比较。