Variable name as a string in Javascript

前端 未结 17 1522
难免孤独
难免孤独 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 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]
    

提交回复
热议问题