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

TypeScript递归遍历对象及博客评论消息统计函数修复问题

TypeScript递归遍历对象及博客评论消息统计函数修复问题

看起来你已经摸到递归遍历嵌套评论的门道了,不过第二个尝试里漏了一个关键细节——当前评论本身的message也得算进去!这就是为什么统计结果不对的核心原因。

问题出在哪?

咱们看你的第二个函数:

let traverseComment = (param: BlogComment): number => {
  let result = 0;
  if (param.replies == null) result = 1;
  else {
    param.replies.forEach((comment) => {
      result += traverseComment(comment);
    });
  }
  return result;
};

当处理带有replies的评论时,你把result初始化为0,然后只累加了所有回复的统计数,但完全没把当前这条评论自己的1条message加进去。比如处理comments[0]时:

  • 它的replies是[11,12],你遍历这两个评论,累加它们的统计结果
  • 但comments[0]自己的message("Hey dude")完全没被计数,而且每个子评论的统计也犯了同样的错误(比如comment11的统计只算了它的两个回复,没算自己)

修复后的递归函数

我们只需要调整逻辑:不管有没有回复,先把当前评论的1条message算上,再累加所有回复的消息总数:

type BlogComment = { id: number; message: string; replies?: BlogComment[]; };

let traverseComment = (param: BlogComment): number => {
  // 先统计当前评论的1条消息
  let totalMessages = 1;
  
  // 如果存在非空的回复列表,遍历每个回复并累加总数
  if (param.replies?.length) {
    param.replies.forEach(reply => {
      totalMessages += traverseComment(reply);
    });
  }
  
  return totalMessages;
};

测试验证

  • 调用traverseComment(comments[1]):返回1,正确对应"Good morning folks!!"这条消息
  • 调用traverseComment(comments[0]):返回6,正确覆盖id1、11、111、112、12、121这6条消息

额外:统计所有评论的总消息数

如果需要一次性统计整个comments数组的所有7条消息,可以再写个辅助函数:

const countAllCommentMessages = (comments: BlogComment[]): number => {
  return comments.reduce((total, comment) => total + traverseComment(comment), 0);
};

// 调用示例
console.log(countAllCommentMessages(comments)); // 输出7,完全正确

小优化建议

用param.replies?.length代替param.replies == null,这样可以兼容replies是空数组[]的情况(避免不必要的遍历),同时用可选链操作符也更符合TypeScript的安全编码习惯。

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.08 09:14:52