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

使用jQuery开发日历时输出[Object object]而非数字的问题排查

jQuery日历开发:解决对象数值显示问题

我正尝试用jQuery开发日历,但不知道怎么让对象显示出它的数值。试过用JSON.toString()处理表格数据,但没解决问题,可能是toString放错位置了?

使用toString前的代码

// 获取当月天数
let daysInMonth = new Date(this.displayDate.getFullYear(), this.displayDate.getMonth() + 1, 0).getDate();

// 生成要显示的日期数组
let days = [];
for (let i = 1; i <= daysInMonth; i++) {
  days.push(new Date(displayDate.getFullYear(), displayDate.getMonth(),i));
}

console.log(this.monthNames[this.displayDate.getMonth()] + " " + this.displayDate.getFullYear());

td = $("<td>").attr("class", "day").text(days[i].getDate());
td.append(td);

错误的尝试代码

td = $("<td>").attr("class", "day").text(days[i].getDate());
td.append(JSON.stringify("td"));

问题分析与解决方案

你的代码存在几个关键问题:

  • 索引越界:生成days数组的循环结束后,i的值已经是daysInMonth + 1,此时访问days[i]会拿到undefined,直接调用getDate()会报错。
  • 无效DOM操作:创建td元素后将它追加到自身上,这是错误逻辑,应该把td添加到表格的行(tr)或主体(tbody)中。
  • 无用的JSON处理:JSON.stringify("td")只是把字符串"td"转成JSON格式,和显示日期数值的需求完全无关。你已经用getDate()拿到了日期的数字值,根本不需要额外的JSON处理。

修正后的代码示例

// 获取当月天数
let daysInMonth = new Date(this.displayDate.getFullYear(), this.displayDate.getMonth() + 1, 0).getDate();

// 生成要显示的日期数组
let days = [];
for (let i = 1; i <= daysInMonth; i++) {
  // 注意使用this.displayDate,避免作用域丢失
  days.push(new Date(this.displayDate.getFullYear(), this.displayDate.getMonth(), i));
}

// 格式化打印年月
console.log(`${this.monthNames[this.displayDate.getMonth()]} ${this.displayDate.getFullYear()}`);

// 假设页面中有id为calendar-tbody的tbody容器
const $calendarTbody = $("#calendar-tbody");
$calendarTbody.empty(); // 清空原有内容

let $currentRow = $("<tr>");
// 遍历日期数组生成每个日期的td
for (let j = 0; j < days.length; j++) {
  const $dayTd = $("<td>").attr("class", "day").text(days[j].getDate());
  $currentRow.append($dayTd);

  // 每7个日期换一行(模拟每周7天)
  if ((j + 1) % 7 === 0) {
    $calendarTbody.append($currentRow);
    $currentRow = $("<tr>");
  }
}

// 添加最后一行剩余的日期
if ($currentRow.children().length > 0) {
  $calendarTbody.append($currentRow);
}

关键说明

  1. 遍历days数组时使用独立的索引变量(比如j),避免和生成数组的循环变量i冲突。
  2. 将生成的td元素追加到表格的行中,再把行追加到tbody,完成正确的DOM结构构建。
  3. 如果需要查看Date对象的详细信息,可以直接用console.log(days[j]),或者用JSON.stringify(days[j])转成JSON字符串,但显示日期数值时getDate()已经足够。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 00:15:36