You need to enable JavaScript to run this app. 如何在Ionic Angular或JavaScript中筛选出当年当前月及之后的剩余月份
优惠活动
大模型
产品
解决方案
定价
更多

如何在Ionic Angular或JavaScript中筛选出当年当前月及之后的剩余月份

从当前月份开始展示当年剩余月份的实现方法

JavaScript内置Date对象的getMonth()方法返回值范围为0(对应1月)到11(对应12月),和你定义的月份数组的索引完全一一对应,不需要做字符串匹配查找当前月位置,直接通过数组切片就能拿到需要展示的剩余月份列表。

具体实现代码

纯JavaScript场景

// 你已定义的月份数组
const month = ['January', 'February', 'March', 'April', 'May', 'June', 'July',
    'August', 'September', 'October', 'November', 'December'];

// 获取当前月对应的数组索引
const currentMonthIndex = new Date().getMonth();

// 从当前月索引位置开始截取到数组末尾,即为剩余待展示的月份
const remainingMonths = month.slice(currentMonthIndex);

实际运行效果参考:如果当前是9月(getMonth()返回值为8),截取后的结果就会从September开始,一直到December结束,自动过滤掉January到August这些已经过去的月份。

Ionic Angular场景

在组件类中定义属性,在生命周期钩子里完成逻辑计算:

// 组件类属性定义
month = ['January', 'February', 'March', 'April', 'May', 'June', 'July',
    'August', 'September', 'October', 'November', 'December'];

// 供模板绑定的剩余月份列表
remainingMonths: string[] = [];

ngOnInit() {
  const currentMonthIndex = new Date().getMonth();
  // 切片得到剩余月份,赋值给可绑定属性
  this.remainingMonths = this.month.slice(currentMonthIndex);
}

直接在模板中循环渲染即可:

<ion-list>
  <ion-item *ngFor="let monthName of remainingMonths">
    {{ monthName }}
  </ion-item>
</ion-list>

实用调整说明

  • 不需要通过之前写的currentMonth字符串值调用indexOf查找位置,这种写法不仅冗余,还容易因为月份拼写不一致引发运行时错误
  • 数组slice方法不会修改原月份数组,不会对其他依赖原数组的业务逻辑产生副作用
  • 如果需要展示中文月份,只需要把原month数组的内容替换为中文月份名即可,切片逻辑完全不需要改动,示例:
// 替换为中文月份数组,逻辑保持一致
const month = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];
const remainingMonths = month.slice(new Date().getMonth());

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.27 23:06:03