Variable name as a string in Javascript

前端 未结 17 1450
难免孤独
难免孤独 2020-11-22 06:20

Is there a way to get a variable name as a string in Javascript? (like NSStringFromSelector in Cocoa)

I would like to do like this:

var myFirstName =         


        
相关标签:
17条回答
  • 2020-11-22 06:38

    I've created this function based on JSON as someone suggested, works fine for my debug needs

    function debugVar(varNames){
    let strX = "";
    function replacer(key, value){
        if (value === undefined){return "undef"}
        return value
        }    
    for (let arg of arguments){
    let lastChar;
        if (typeof arg!== "string"){
            let _arg = JSON.stringify(arg, replacer);
            _arg = _arg.replace('{',"");
            _arg = _arg.replace('}',"");            
            _arg = _arg.replace(/:/g,"=");
            _arg = _arg.replace(/"/g,"");
            strX+=_arg;
        }else{
        strX+=arg;
        lastChar = arg[arg.length-1];
        }
        if (arg!==arguments[arguments.length-1]&&lastChar!==":"){strX+=" "};
    }
    console.log(strX)    
    }
    let a = 42, b = 3, c;
    debugVar("Begin:",{a,b,c},"end")

    0 讨论(0)
  • 2020-11-22 06:41

    No, there is not.
    Besides, if you can write variablesName(myFirstName), you already know the variable name ("myFirstName").

    0 讨论(0)
  • 2020-11-22 06:43

    Shorts way I have found so far to get the variables name as a string:

    const name = obj => Object.keys(obj)[0];
    
    const whatsMyName = "Snoop Doggy Dogg";
    
    console.log( "Variable name is: " + name({ whatsMyName }) );
    //result: Variable name is: whatsMyName

    0 讨论(0)
  • 2020-11-22 06:44

    Probably pop would be better than indexing with [0], for safety (variable might be null).

    const myFirstName = 'John'
    const variableName = Object.keys({myFirstName}).pop();
    console.log(`Variable ${variableName} with value '${variable}'`);
    
    // returns "Variable myFirstName with value 'John'"
    
    0 讨论(0)
  • 2020-11-22 06:44

    Since ECMAScript 5.1 you can use Object.keys to get the names of all properties from an object.

    Here is an example:

    // Get John’s properties (firstName, lastName)
    var john = {firstName: 'John', lastName: 'Doe'};
    var properties = Object.keys(john);
    
    // Show John’s properties
    var message = 'John’s properties are: ' + properties.join(', ');
    document.write(message);

    0 讨论(0)
  • 2020-11-22 06:45

    Like Seth's answer, but uses Object.keys() instead:

    const varToString = varObj => Object.keys(varObj)[0]
    
    const someVar = 42
    const displayName = varToString({ someVar })
    console.log(displayName)

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