Variable name as a string in Javascript

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

    In ES6, you could write something like:

    let myVar = 'something';
    let nameObject = {myVar};
    let getVarNameFromObject = (nameObject) => {
      for(let varName in nameObject) {
        return varName;
      }
    }
    let varName = getVarNameFromObject(nameObject);
    

    Not really the best looking thing, but it gets the job done.

    This leverages ES6's object destructuring.

    More info here: https://hacks.mozilla.org/2015/05/es6-in-depth-destructuring/

提交回复
热议问题