Variable name as a string in Javascript

前端 未结 17 1819
难免孤独
难免孤独 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:49

    var somefancyvariable = "fancy";
    Object.keys({somefancyvariable})[0];
    

    This isn't able to be made into a function as it returns the name of the function's variable.

    // THIS DOESN'T WORK
    function getVarName(v) {
        return Object.keys({v})[0];
    }
    // Returns "v"
    

    Edit: Thanks to @Madeo for pointing out how to make this into a function.

    function debugVar(varObj) {
        var varName = Object.keys(varObj)[0];
        console.log("Var \"" + varName + "\" has a value of \"" + varObj[varName] + "\"");
    }
    

    You will need call the function with a single element array containing the variable. debugVar({somefancyvariable});
    Edit: Object.keys can be referenced as just keys in every browser I tested it in but according to the comments it doesn't work everywhere.

提交回复
热议问题