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

按当前月份过滤含date属性的对象数组报错m.getTime is not a function求助

Fixing "m.getTime is not a function" & Filtering Events for the Current Month

Hey there! Let's break down why you're hitting that error and get your current-month events displaying correctly.

What's Causing the Error?

Your existing code has two critical issues that lead to the m.getTime is not a function error:

  • You immediately overwrite the loop variable m with new Date() inside the loop, completely replacing the original event object from this.monthEvent. You never actually use the date property from your event data!
  • You return this.thisMonth inside the loop, so the loop stops after the first iteration—you’ll never check all events in the array.

Corrected Solution

Instead of juggling a manual loop and variable overwrites, use JavaScript's filter() method to cleanly select events from the current month. Here's the fixed code:

// Get current month (note: getMonth() returns 0 for January, 11 for December)
const currentMonth = new Date().getMonth();
const currentYear = new Date().getFullYear(); // Add this to match the current year too

// Filter events to keep only those from the current month (and year, if needed)
this.thisMonth = this.monthEvent.filter(event => {
  // Convert the event's date string to a valid Date object
  const eventDate = new Date(event.date);
  
  // Compare month (and optional year) to current values
  return eventDate.getMonth() === currentMonth 
         && eventDate.getFullYear() === currentYear; // Remove this line if year doesn't matter
});

Key Improvements

  • We’re actually using the date property from each event object to create a Date instance, instead of overwriting the loop variable.
  • The filter() method automatically iterates through the entire array and returns only matching elements—no manual loop management required.
  • Added an optional year check to ensure you’re only getting events from this year's current month (prevents pulling in events from the same month last year, which is likely what you want).

Why Your Original Code Failed

Let’s recap the missteps in your original code to avoid them later:

for (let m of this.monthEvent){ 
  m=new Date(); // ❌ Overwrites the event object with a new Date—you lose the original event's date!
  if(m.getMonth() === new Date().getMonth()){ 
    this.thisMonth=m; 
  } 
  return this.thisMonth; // ❌ Exits the loop after the first iteration
}

By overwriting m, you’re no longer working with the event objects from your array. When the code tries to process m, it’s not the object you expected, leading to the getTime error (which runs internally when Date methods execute).

内容的提问来源于stack exchange,提问作者Mohammed Abdul kadhir

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:18:14