Get the name of a variable (like nameof operator in C#) [duplicate]

百般思念 提交于 2019-11-29 12:43:09

问题


Let's assume we have the following code:

const myVariable = { age: 7, name: "Hunter" };

I want to know the name of the variable, not just the value of it, and put it in a string or log it or:

const s = nameof(myVariable) + ': ' + JSON.stringify(myVariable);

And the result I want to see is sth like:

"myVariable: {"age":7,"name":"Hunter"}"

Looking forward to see your solution.


回答1:


This is my own answer in Q&A style which comes with a bit of a compromise. The trick is here to pass the parameter to the function nameof inside an object by enclosing it in curly braces, like this nameof({myVariable}) instead of nameof(myVariable).

Following this convention, the solution can look like this:

var HD = HD || {};
HD.nameof = function (obj) {
  return Object.keys(obj)[0];
}

And this is how I use it to get the name of the variable/object plus the object's content/the variable's value:

const s = HD.nameof({myVariable}) + ': ' + JSON.stringify(myVariable);   

Thus, s will contain the result as requested in the question above.



来源:https://stackoverflow.com/questions/37057211/get-the-name-of-a-variable-like-nameof-operator-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!