【问题标题】:How to change the value of js local variable when debug in Chrome console在 Chrome 控制台中调试时如何更改 js 局部变量的值
【发布时间】:2026-01-10 22:40:02
【问题描述】:

当我使用 Chrome 控制台调试 javascript 时,我想更改函数的局部变量。我知道如何更改全局变量的值,但是在 Chrome 控制台中调试时如何更改局部变量的值?

【问题讨论】:

    标签: javascript debugging


    【解决方案1】:

    您不会在 Chrome 控制台中调试。您在 Chrome 调试器中进行调试。如果您在调试器的断点处停止,您可以使用控制台通过分配给它来更改任何范围内变量的值。

    例如,打开开发工具并运行此代码,读取 cmets:

    function foo() {
      var bar = 42;
      // Normally, you don't have to use a hardcoded breakpoint like
      // the one that follows, you can set a breakpoint from within the
      // debugger just by navigating to the line of code and clicking in
      // the left-hand gutter. But in Stack Snippets the easiest way to
      // do one is to use the debugger statement:
      debugger;
      // Now, when stopped on the breakpoint, type this in the console:
      // bar = 67;
      // ...and press Enter.
      // Then hit the arrow button to allow the script to continue
      console.log(bar); // ...and this will log 67 instead of 42.
    }
    foo();

    【讨论】:

      【解决方案2】:

      尝试设置一个断点,您希望将局部变量的值重新定义为不同的值。然后您可以访问该范围内的所有数据。

      这可能会有所帮助

      【讨论】:

      • 我想要的是第二次记录 13。
      • 第二次是什么意思,当您在该范围内时,您可以编写任意数量的 console.log 语句,它仍然会打印 13,如果您说当您再次运行代码时第二次,如果要将其记录为 13,则必须确保将变量再次设置为 13