获取变量的名称(如C#中的nameof运算符) [英] Get the name of a variable (like nameof operator in C#)

查看:744
本文介绍了获取变量的名称(如C#中的nameof运算符)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们假设我们有以下代码:

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.

推荐答案

这是我自己的回答Q& A风格,带有一点妥协。诀窍在于将参数传递给对象内部的函数名称,方法是将其括在花括号中,例如 nameof({myVariable})而不是 nameof(myVariable)

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);   

因此,s将包含上述问题中所要求的结果。

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

这篇关于获取变量的名称(如C#中的nameof运算符)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆