Print / display a JavaScript variable's name instead of it's value

前端 未结 3 1106
一整个雨季
一整个雨季 2020-12-01 18:53

Is it possible to print / display a JavaScript variable\'s name? For example:

var foo=5;
var bar=6;
var foobar=foo+bar;

document.write(foo+ \"
\");
相关标签:
3条回答
  • Utils = {
        eventRegister_globalVariable : function(variableName,handlers){
            eventRegister_JsonVariable(this,variableName,handlers);
        },
        eventRegister_jsonVariable : function(jsonObj,variableName,handlers){
            if(jsonObj.eventRegisteredVariable === undefined) {
                jsonObj.eventRegisteredVariable={};//this Object is used for trigger event in javascript variable value changes ku
            }
            Object.defineProperty(jsonObj, variableName , {
                        get: function() { 
                            return jsonObj.eventRegisteredVariable[variableName] },
                        set: function(value) {
                            jsonObj.eventRegisteredVariable[variableName] = value; handlers(jsonObj.eventRegisteredVariable[variableName]);}
                        });
                }
    
    0 讨论(0)
  • 2020-12-01 19:13

    You can put the variables in an object then easily print them this way: http://jsfiddle.net/5MVde/7/

    See fiddle for everything, this is the JavaScript...

    var x = {
        foo: 5,
        bar: 6,
        foobar: function (){
            var that=this;
            return that.foo+that.bar
        }
    };
    
    var myDiv = document.getElementById("results");
    
    myDiv.innerHTML='Variable Names...';
    for(var variable in x)
    {
        //alert(variable);
        myDiv.innerHTML+='<br>'+variable;
    }
    
    myDiv.innerHTML+='<br><br>And their values...';
    myDiv.innerHTML+='<br>'+x.foo+'<br>'+x.bar+'<br>'+x.foobar();
    

    The JavaScript for...in statement loops through the properties of an object.

    Another variation (thanks @elclanrs) if you don't want foobar to be a function: http://jsfiddle.net/fQ5hE/2/

    0 讨论(0)
  • 2020-12-01 19:20

    Another possible solution can be "Object.keys(this)".... This will give you all the variable names in an array.

    0 讨论(0)
提交回复
热议问题