Variable name as a string in Javascript

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

    I needed this, don't want to use objects, and came up with the following solution, turning the question around.

    Instead of converting the variable name into a string, I convert a string into a variable.

    This only works if the variable name is known of course.

    Take this:

    var height = 120;
    testAlert(height);
    

    This should display:

    height: 120
    

    This can be done like this:

    function testAlert(ta)
    {
        a = window[ta];
        alert(ta + ': ' + a); 
    }
    
    var height = 120;
    testAlert("height");
    // displays: height: 120
    

    So I use the string "height" and turn that into a variable height using the window[] command.

提交回复
热议问题