Javascript - 转储所有全局变量 [英] Javascript - dumping all global variables

查看:152
本文介绍了Javascript - 转储所有全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Javascript中有没有办法获取列表或转储Javascript / jQuery脚本在页面上声明的所有全局变量的内容?我对数组特别感兴趣。如果我能得到阵列名称,那对我来说就足够了。看到它的价值是一个额外的好处。

Is there a way in Javascript to get a list or dump the contents of all global variables declared by Javascript/jQuery script on a page? I am particularly interested in arrays. If I can get the array names, it will be enough to me. Seeing its values is a bonus.

推荐答案

Object.keys( window );

这将为您提供<$的所有可枚举属性的数组c $ c> window object,(全局变量)。

This will give you an Array of all enumerable properties of the window object, (which are global variables).

对于旧版浏览器,请包含来自MDN的兼容性补丁

For older browsers, include the compatibility patch from MDN.

要查看其值,那么显然您只需要一个典型的枚举器,例如 for-in

To see its values, then clearly you'll just want a typical enumerator, like for-in.

您应该注意我提到这些方法只会为您提供 可枚举的 属性。通常那些不是环境内置的那些。

You should note that I mentioned that these methods will only give you enumerable properties. Typically those will be ones that are not built-in by the environment.

可以在ES5支持的浏览器中添加不可枚举的属性。这些将不包含在 Object.keys 中,或者使用 for-in 语句时。

It is possible to add non-enumerable properties in ES5 supported browsers. These will not be included in Object.keys, or when using a for-in statement.

@Raynos 所述,对于非枚举,你可以 Object.getOwnPropertyNames(window)。我不知道。谢谢@Raynos!

As noted by @Raynos, you can Object.getOwnPropertyNames( window ) for non-enumerables. I didn't know that. Thanks @Raynos!

所以要查看包含enumerables的值,你需要这样做:

So to see the values that include enumerables, you'd want to do this:

var keys = Object.getOwnPropertyNames( window ),
    value;

for( var i = 0; i < keys.length; ++i ) {
    value = window[ keys[ i ] ];
    console.log( value );
}

这篇关于Javascript - 转储所有全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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