Javascript - dumping all global variables

后端 未结 8 1909
迷失自我
迷失自我 2020-11-28 05:39

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 array

8条回答
  •  南方客
    南方客 (楼主)
    2020-11-28 06:06

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

提交回复
热议问题