按当前月份过滤含date属性的对象数组报错m.getTime is not a function求助
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
mwithnew Date()inside the loop, completely replacing the original event object fromthis.monthEvent. You never actually use thedateproperty from your event data! - You return
this.thisMonthinside 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
dateproperty from each event object to create aDateinstance, 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

