调试:是否可以实时查看JS变量的值? [英] Debugging: Is it possible to see value of JS variable in real time?

查看:62
本文介绍了调试:是否可以实时查看JS变量的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何工具(最好是任何浏览器的扩展/附加程序)可让您实时查看所需JS变量的所有值变化?

Is there any tool (preferably extension/add-on to any browser) that allows you to see all the value changes of the desired JS variable in real time?

以前我做过这样的事情(在纯JS中):

Previously I did something like this (in pure JS):

var someVariable;
var previousValueOfSomeVariable;
var f = function() {
  if (previousValueOfSomeVariable != someVariable) {
    console.log(Date.now(), someVariable);
    previousValueOfSomeVariable = someVariable;
  }
}
var TO = setInterval(f, 100);

它可以解决问题,但是效率很低(实际上,函数更大,而如果变量是对象,则需要对象复制功能并进一步检查)...

It did the trick, but was, of course, inefficient (in reality the function was bigger, while it required object-copy function if variable was an object and further checks)...

更新

我知道控制台工具,但是我想查看更改的历史记录,例如:

I'm aware of console tools, but I'd like to see the history of changes, like:

someVariable

0ms:未定义

10ms: 5 ;

40ms:'someothervalue';

150ms: null

(以毫秒为示例目的,不一定是必需的).也许可以在DevTools控制台中完成,但我不知道如何.

(Milliseconds are given for example purposes, not necessarily required). Maybe it can be done within the DevTools console, but I don't know how.

推荐答案

不同的DevTools(在Chrome DevTools,Firefox DevTools和Firebug中进行了测试)无法提供实时查看值变化的方法.您始终必须手动刷新其显示.

The different DevTools (tested in Chrome DevTools, Firefox DevTools and Firebug) don't offer a way to see the value changes in real time. You always have to refresh their display manually.

Firefox提供了 Object.prototype.watch() 函数(对于其他浏览器,有垫片),该函数做你想要的.

Firefox offers an Object.prototype.watch() function (for other browsers there is a shim), which does what you want.

test = 0;
setInterval(() => test++, 1000);

window.watch("test", (id, oldValue, newValue) => {
  console.log(new Date().toLocaleTimeString(), newValue);
  return newValue;
});

这将输出如下内容:

09:51:03 1
09:51:04 2
09:51:05 3
09:51:06 4
09:51:07 5

09:51:03 1
09:51:04 2
09:51:05 3
09:51:06 4
09:51:07 5

注意:此函数仅允许监视对象的单个属性,因此,要监视所有对象属性,您需要遍历它们并为每个对象调用 watch()

这篇关于调试:是否可以实时查看JS变量的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆