Variable name as a string in Javascript

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

    Probably pop would be better than indexing with [0], for safety (variable might be null).

    const myFirstName = 'John'
    const variableName = Object.keys({myFirstName}).pop();
    console.log(`Variable ${variableName} with value '${variable}'`);
    
    // returns "Variable myFirstName with value 'John'"
    

提交回复
热议问题