Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
158 views
in Technique[技术] by (71.8m points)

jquery - Javascript - dumping all global variables

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.

question from:https://stackoverflow.com/questions/8369338/javascript-dumping-all-global-variables

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Object.keys( window );

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

For older browsers, include the compatibility patch from MDN.


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.

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.


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

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 );
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...