Skip to content
当前页导航

ChatGPT 代码调试

使用 ChatGPT 调试代码

使用 ChatGPT 编写代码就像让经验丰富的程序员检查您的代码一样。

在您自己的代码中发现错误可能很困难,在其他人编写的代码中发现错误则更困难。

ChatGPT 可以为您节省大量调试代码的时间。

缩小问题范围

在使用生成式人工智能来帮助您之前,看看是否可以缩小问题范围并收集更多信息。

弄清楚(如果可以的话):

  • 代码的哪一部分导致了错误?
  • 有错误信息吗?
  • 发生了什么以及应该发生什么?

ChatGPT可以通过更多信息更准确地找到问题。

问题代码

上一章,我们让 ChatGPT 为我们编写了一些网页代码。现在我们在页面中添加了新的设计,代码不再起作用:

问题代码

html
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
</head>
<body>

<h1>My First Web Page</h1>

<p></p>

<script>
  function countdownOrWeekendMessage() {
    const now = new Date();
    const targetDate = new Date();

    // 获取当前日期是星期几(0表示星期日,1表示星期一,依次类推)
    const currentDay = now.getDay();

    // 设置目标日期为下周六(星期六对应的数字是6)
    targetDate.setDate(now.getDate() + (6 - currentDay + 7) % 7 + 7);

    // 设置目标日期的时、分、秒为0,以确保只计算到日期的差异
    targetDate.setHours(0, 0, 0, 0);

    // 判断当前日期是否为周六
    if (currentDay === 6) {
      document.getElementById("weekend_message").innerHTML = "周末已经到来!";
    } else {
      const timeLeft = targetDate.getTime() - now.getTime();

      const days = Math.floor(timeLeft / (1000 * 60 * 60 * 24));
      const hours = Math.floor((timeLeft % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));

      document.getElementById("weekend_message").innerHTML = `周末还有 ${days}${hours} 小时`;
    }
  }

  // 每秒钟更新一次倒计时或周末消息
  setInterval(countdownOrWeekendMessage, 1000);

  // 页面加载时立即计算倒计时或显示周末消息
  countdownOrWeekendMessage();
</script>

</body>
</html>

我们不知道我们更改了代码的哪一部分,如果我们按 F12(或进入浏览器的开发人员模式),我们可以在“控制台”中看到错误:

Uncaught TypeError: Cannot set properties of null (setting 'innerText') at countdownToSaturday

有了这些信息,我们就可以让 ChatGPT 进行调试。

输入

一下网页的倒计时功能不起作用。
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
</head>
<body>

<h1>My First Web Page</h1>

<p></p>

<script>
  function countdownOrWeekendMessage() {
    const now = new Date();
    const targetDate = new Date();

    // 获取当前日期是星期几(0表示星期日,1表示星期一,依次类推)
    const currentDay = now.getDay();

    // 设置目标日期为下周六(星期六对应的数字是6)
    targetDate.setDate(now.getDate() + (6 - currentDay + 7) % 7 + 7);

    // 设置目标日期的时、分、秒为0,以确保只计算到日期的差异
    targetDate.setHours(0, 0, 0, 0);

    // 判断当前日期是否为周六
    if (currentDay === 6) {
      document.getElementById("weekend_message").innerHTML = "周末已经到来!";
    } else {
      const timeLeft = targetDate.getTime() - now.getTime();

      const days = Math.floor(timeLeft / (1000 * 60 * 60 * 24));
      const hours = Math.floor((timeLeft % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));

      document.getElementById("weekend_message").innerHTML = `周末还有 ${days} 天 ${hours} 小时`;
    }
  }

  // 每秒钟更新一次倒计时或周末消息
  setInterval(countdownOrWeekendMessage, 1000);

  // 页面加载时立即计算倒计时或显示周末消息
  countdownOrWeekendMessage();
</script>

</body>
</html>
我得到以下错误:
Uncaught TypeError: Cannot set properties of null (setting 'innerText')
at countdownToSaturday

输出chat-26.jpg

查看代码

查看 ChatGPT 的响应,它似乎可能有效。

我们不小心删除了应该显示文本的元素。将正确的 ID 添加到新元素应该可以工作。

测试

将修复添加到代码中并进行测试:

html
<p id="weekend_message"></p>