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

使用JavaScript的includes()筛选数组内数字时报错(TypeError),求解决方案

解决筛选2022年活动的报错问题

报错原因

你遇到的TypeError: periodArray.includes is not a function,核心问题是**element.years并非始终是数组**——虽然你提供的示例数据里都是数组,但实际运行时可能存在某个活动的years值为null、undefined、字符串或其他非数组类型,导致无法调用数组的includes方法。

正确实现方式

在调用includes前先校验element.years的类型,确保它是数组再执行判断:

const activities2022 = activities.filter((element) => {
  const periodArray = element.years;
  // 先验证数组类型,再检查是否包含2022
  return Array.isArray(periodArray) && periodArray.includes(2022);
});

其他解决思路

  • 用indexOf替代includes:兼容更老旧的浏览器(若有需求),逻辑和includes一致:
const activities2022 = activities.filter((element) => {
  const periodArray = element.years;
  return Array.isArray(periodArray) && periodArray.indexOf(2022) !== -1;
});
  • 预处理标准化数据:如果数据来源不可控,先统一格式,确保所有years都是数组:
// 预处理:将非数组的years转为空数组
const normalizedActivities = activities.map(item => ({
  ...item,
  years: Array.isArray(item.years) ? item.years : []
}));

// 再执行筛选
const activities2022 = normalizedActivities.filter(item => item.years.includes(2022));
  • 用some方法自定义判断:适合需要扩展判断逻辑的场景(比如年份范围匹配),基础用法和includes等价:
const activities2022 = activities.filter((element) => {
  const periodArray = element.years;
  return Array.isArray(periodArray) && periodArray.some(year => year === 2022);
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 13:28:11