Variable name as a string in Javascript

前端 未结 17 1741
难免孤独
难免孤独 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: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);

提交回复
热议问题