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

Angular 4开发遇findIndex不是函数问题,求TypeScript中配置方法

解决Angular 4中findIndex相关报错的方案

嘿,作为Angular新手碰到这些数组方法的报错太正常了,我帮你一步步拆解解决:

一、原生数组findIndex()提示“is not a function”的问题

这个报错本质是你调用findIndex的对象this.selectedDates根本不是数组,常见原因有这几个:

  • 组件初始化时selectedDates没设为数组(比如是undefined/null)
  • 异步加载的日期数据还没返回,导致调用方法时selectedDates还是空值
  • 后端返回的selectedDates是类数组对象(比如NodeList或者自定义对象)

解决步骤:

  1. 确保selectedDates初始化为数组:在组件类里直接声明并初始化:
selectedDates: any[] = []; // 或者根据你的业务改成Moment类型数组,比如Moment[]
  1. 调用前先做类型校验:在isSelected方法里先判断是否为有效数组,避免空指针:
isSelected(date: moment.Moment): boolean {
  // 先校验数组有效性
  if (!Array.isArray(this.selectedDates) || this.selectedDates.length === 0) {
    return false;
  }
  // 再调用原生findIndex
  const index = this.selectedDates.findIndex(selectedDate => {
    return moment(date).isSame(selectedDate.mDate, 'day'); // 注意你写的'day...'多了三个点,要改成'day'
  });
  return index !== -1;
}

二、Lodash的_.findIndex提示“is not a function”的问题

这个是Lodash的导入方式错误导致的,Angular/Webpack环境下,直接导入_可能没正确加载到所有方法,或者你用的是按需导入但配置不对。

解决步骤:

有两种靠谱的导入方式:

  1. 完整导入Lodash:在组件顶部改成:
import * as _ from 'lodash';

这样_.findIndex就能正常使用了。

  1. 按需导入单个方法(更轻量化):只导入你需要的findIndex,减少打包体积:
import { findIndex } from 'lodash';

然后修改isSelected方法的调用:

isSelected(date: moment.Moment): boolean {
  if (!Array.isArray(this.selectedDates) || this.selectedDates.length === 0) {
    return false;
  }
  const index = findIndex(this.selectedDates, selectedDate => {
    return moment(date).isSame(selectedDate.mDate, 'day');
  });
  return index !== -1;
}

额外注意点

你代码里的'day...'是语法错误,要改成'day',否则moment.isSame也会出问题哦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:16:37