Variable name as a string in Javascript

前端 未结 17 1838
难免孤独
难免孤独 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: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'.

提交回复
热议问题