Array includes返回false但元素存在,求问题原因及非循环判断方案
问题分析与解决方案
出错原因
核心问题是类型不匹配:
moment.unix(curr_time).format('e')返回的是字符串类型的'6',但你的数组weekends_test里存的是数字类型的6和5。- JavaScript的
includes()和indexOf()都是用严格相等(===)做判断,字符串和数字类型不同,自然匹配失败。
修复方法
两种简单的修复方式任选其一:
- 把moment返回的结果转为数字:
let day_of_week_curr = Number(moment.unix(curr_time).format('e')); // 或者用parseInt更严谨 let day_of_week_curr = parseInt(moment.unix(curr_time).format('e'), 10);
- 把数组里的元素改为字符串:
let weekends_test = ['6', '5'];
除for循环外的其他判断方法
除了includes()和indexOf(),还有这些实用方法:
some()方法:检查数组中是否存在满足条件的元素,支持自定义判断逻辑
// 用==自动做类型转换,或者手动转类型后用=== const exists = weekends_test.some(item => item == day_of_week_curr);
find()方法:返回第一个符合条件的元素,若存在则结果不为undefined
const foundItem = weekends_test.find(item => item == day_of_week_curr); const exists = foundItem !== undefined;
Set结构:先把数组转为Set,利用Set的has()方法快速判断,适合需要多次查询的场景
const weekendSet = new Set(weekends_test); const exists = weekendSet.has(Number(day_of_week_curr));
内容的提问来源于stack exchange,提问作者Владислав Светайло
相关产品推荐
相关产品推荐

