JavaScript:如何获取常量的名称? [英] JavaScript: How to get name of the constant?

查看:38
本文介绍了JavaScript:如何获取常量的名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取常量的名称:

const MY_CONSTANT = 1;

我想显示常量(MY_CONSTANT)的名称而不是值(1).

I want to show the name of my constant (MY_CONSTANT) not value (1).

推荐答案

您无法在JavaScript中获得常量或变量的名称.与您要执行的操作最接近的事情是在对象内设置属性.然后,您可以获得所有键的名称.

You cannot get the name of the constant or a variable in JavaScript. The closest thing to what you want to do would be setting a property inside an object. Then, you can get the names of all keys.

var obj = { myFirstName: 'John' };
obj.foo = 'Another name';
for(key in obj)
    alert(key + ': ' + obj[key]);

此处

这篇关于JavaScript:如何获取常量的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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