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

Vue获取周数时报Cannot read properties of undefined (reading 'valueOf')错误如何解决

错误根因

报错指向getWeekNumber函数第一行的date.valueOf()调用,说明该函数接收的入参date为undefined。你观察到控制台可正常打印formated_date的有效值,属于以下两种常见的开发误判场景:

  • Array.filter会遍历整个products数组,部分数组项的product.attributes.date为无效值,导致this.setDateFormat()返回了undefined或者非Date类型的异常值。控制台打印的是所有遍历项的结果,你可能只注意到了正常项的输出,或是受浏览器控制台异步渲染的特性影响,展开打印内容时展示的是计算完成后的最终值,掩盖了瞬时无效值的状态。
  • 逻辑与&&为短路执行逻辑:只有前面三个判断formated_date和入参date年月日相等的条件全部成立时,才会执行后续的this.getWeekNumber调用。如果formated_date是格式匹配的字符串、你自行给字符串扩展了getDate/getMonth等方法,就会出现前面判断可正常执行、传入getWeekNumber的参数实际不符合Date类型要求的情况。

修复方案

可以同时从入参校验和函数兜底两个维度处理:

  1. 调用getWeekNumber前新增合法性校验
findProducts(products, date) {
  return products.filter((product) => {
    const formated_date = this.setDateFormat(product.attributes.date);
    return (
      // 先校验formated_date是合法Date对象
      formated_date instanceof Date && 
      !isNaN(formated_date.valueOf()) &&
      formated_date.getDate() === date.getDate() &&
      formated_date.getMonth() === date.getMonth() &&
      formated_date.getFullYear() === date.getFullYear() &&
      this.getWeekNumber(formated_date) === this.currentWeekNumber
    );
  });
}
  1. 给getWeekNumber增加参数兜底逻辑,避免异常崩溃
getWeekNumber(date) {
  // 非法参数直接返回约定的异常值,比如0
  if(!date || !(date instanceof Date) || isNaN(date.valueOf())) return 0
  const temp_date = new Date(date.valueOf());
  const dayn = (date.getDay() + 6) % 7;
  temp_date.setDate(temp_date.getDate() - dayn + 3);
  const firstThursday = temp_date.valueOf();
  temp_date.setMonth(0, 1);
  if (temp_date.getDay() !== 4) {
    temp_date.setMonth(0, 1 + ((4 - temp_date.getDay() + 7) % 7));
  }
  return 1 + Math.ceil((firstThursday - temp_date) / 604800000);
}

额外优化提示

如果你的业务逻辑是筛选和入参date同一天的商品,那么周数判断的逻辑完全冗余——两个年月日完全相同的日期必然属于同一周,可以直接删掉该判断减少不必要的计算。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 06:36:03