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

如何在JavaScript中按选中年份筛选DD/MM/YYYY格式的日期数组

你可以通过监听下拉框的change事件结合数组的filter方法实现需求,以下是可直接运行的实现方案:

const array1 = ['10/10/2020','11/10/2020','12/10/2020','10/10/2021','12/10/2021','12/10/2021'];
const dateSelect = document.getElementById('dates');

// 按选中年份筛选的核心逻辑
function filterDateBySelectedYear() {
  const selectedYear = dateSelect.value;
  // 对日期数组进行过滤
  const matchedDates = array1.filter(dateItem => {
    // 按/拆分日期字符串,取最后一段即为年份
    const itemYear = dateItem.split('/').pop();
    return itemYear === selectedYear;
  });
  // 此处可替换为你的业务逻辑,比如渲染筛选结果到页面
  console.log(matchedDates);
  return matchedDates;
}

// 监听下拉框选择变化,触发筛选
dateSelect.addEventListener('change', filterDateBySelectedYear);
// 页面加载完成后默认执行一次,返回初始选中年份的结果
window.addEventListener('load', filterDateBySelectedYear);

补充说明

  • 如果你的日期格式固定为月/日/年结构,直接用split('/').pop()提取年份的方式足够高效稳定,不需要额外引入第三方日期处理库
  • 若需要兼容其他日期写法,也可以用正则提取年份:dateItem.match(/\d{4}$/)[0],直接匹配字符串末尾的四位数字作为年份
  • filter方法会返回全新的数组,不会修改你原始的array1数据,符合数据不可变的开发规范

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 11:06:03