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

Array includes返回false但元素存在,求问题原因及非循环判断方案

问题分析与解决方案

出错原因

核心问题是类型不匹配:

  • moment.unix(curr_time).format('e') 返回的是字符串类型的'6',但你的数组weekends_test里存的是数字类型的6和5。
  • JavaScript的includes()和indexOf()都是用严格相等(===)做判断,字符串和数字类型不同,自然匹配失败。

修复方法

两种简单的修复方式任选其一:

  1. 把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);
  1. 把数组里的元素改为字符串:
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,提问作者Владислав Светайло

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 23:52:37