Getting All Variables In Scope

前端 未结 10 2154
小蘑菇
小蘑菇 2020-11-22 09:10

Is there a way to get all variables that are currently in scope in javascript?

10条回答
  •  -上瘾入骨i
    2020-11-22 09:51

    Yes and no. "No" in almost every situation. "Yes," but only in a limited manner, if you want to check the global scope. Take the following example:

    var a = 1, b = 2, c = 3;
    
    for ( var i in window ) {
        console.log(i, typeof window[i], window[i]);
    }
    

    Which outputs, amongst 150+ other things, the following:

    getInterface function getInterface()
    i string i // <- there it is!
    c number 3
    b number 2
    a number 1 // <- and another
    _firebug object Object firebug=1.4.5 element=div#_firebugConsole
    "Firebug command line does not support '$0'"
    "Firebug command line does not support '$1'"
    _FirebugCommandLine object Object
    hasDuplicate boolean false
    

    So it is possible to list some variables in the current scope, but it is not reliable, succinct, efficient, or easily accessible.

    A better question is why do you want to know what variables are in scope?

提交回复
热议问题