Variable name as a string in Javascript

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

    You can use the following solution to solve your problem:

    const myFirstName = 'John'
    Object.keys({myFirstName})[0]
    
    // returns "myFirstName"
    
    0 讨论(0)
  • 2020-11-22 06:57

    This works for basic expressions

    const nameof = exp => exp.toString().match(/[.](\w+)/)[1];
    

    Example

    nameof(() => options.displaySize);
    

    Snippet:

    var nameof = function (exp) { return exp.toString().match(/[.](\w+)/)[1]; };
    var myFirstName = 'Chuck';
    var varname = nameof(function () { return window.myFirstName; });
    console.log(varname);

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

    When having a function write a function that changes different global variables values it is not always myfirstname it is whatever happens to be passing through. Try this worked for me.

    Run in jsfiddle

    var jack = 'jill';
    function window_getVarName(what)
    {
      for (var name in window)
      {
        if (window[name]==what)
        return(name);
      }
      return("");
    }
    document.write(window_getVarName(jack));
    

    Will write to the window 'jack'.

    0 讨论(0)
  • 2020-11-22 07:02

    best way using Object.keys();

    example for getting multi variables names in global scope

    // multi varibles for testing
    var x = 5 , b = true , m = 6 , v = "str";
    
    // pass all varibles you want in object
    function getVarsNames(v = {}){
        // getting keys or names !
        let names = Object.keys(v);
        // return array has real names of varibles 
        return names;
    }
    
    //testing if that work or not 
    let VarsNames = getVarsNames({x , b , m , v});
    
    console.log(VarsNames); // output is array [x , b , m , v]
    
    0 讨论(0)
  • 2020-11-22 07:03
    var x = 2;
    for(o in window){ 
       if(window[o] === x){
          alert(o);
       }
    }
    

    However, I think you should do like "karim79"

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