javascript 打印所有变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10233195/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 09:08:43  来源:igfitidea点击:

Print all variables?

javascript

提问by user1342369

I want to do a function that can be used a lot in debugging that print all variables with their values. It would alert:
x=3
y=2

我想做一个可以在调试中大量使用的函数,用于打印所有变量及其值。它会提醒:
x=3
y=2

The function would be like that :
Exemple :

该功能将是这样的: 例如

var text='';
for(var a=0;a<allVariables;a++)
{
    text+=nameOfVariable + " = " + valueOfVariable + "/n";
}
alert(text);

回答by David Gorsline

This will probably do what you're looking for:

这可能会做你正在寻找的:

console.dir(window);

回答by Tronix117

You should use console methods, it's the best for debugging. Quite all modern browsers have the console, and you can use better debugging tools like firebug for firefox. Then a simple console.log(allVariables)and it is all shown in the console.

您应该使用控制台方法,它最适合调试。几乎所有现代浏览器都有控制台,您可以使用更好的调试工具,例如 firebug for firefox。然后一个简单的console.log(allVariables),它都显示在控制台中。

回答by Matt

It can be difficult to determine what "all the variables" are if you use anything global. By default, global variables all fall under the windowscope. So you could loop over all values in window, but that would give you everything elseas well.

如果您使用任何全局变量,可能很难确定“所有变量”是什么。默认情况下,全局变量都属于window作用域。因此,您可以遍历 中的所有值window,但这也会为您提供其他所有内容

If you put everything inside of a namespace, you can be more explicit about it.

如果你把所有东西都放在一个命名空间中,你可以更明确地说明它。

var MyVariables = {
};

MyVariables.foo = 1;
MyVaraibles.hello = 'world';

for(var name in MyVariables){
    console.log(name, MyVariables[name]);
}

Also check out the dev tools available on your browser. I personally would recommend Chrome Dev tools (builtin, F12), or FireBug in FireFox. IE does have some built-ins as well.

还可以查看浏览器上可用的开发工具。我个人会推荐 Chrome 开发工具(内置,F12)或 FireFox 中的 FireBug。IE 也有一些内置插件。