如何在JavaScript中检索变量的名称

How do I retrieve the name of a variable in JavaScript

本文关键字:变量 检索 JavaScript      更新时间:2024-04-18

好吧,假设我有各种各样的变量:

tab = document.createOjbect('table');
str = 'asdf';
ary = [123, 456, 789];
obj = {a:123, b:456, c:789};

一段"字符串化"它们的代码:

function Stringify(){
    var con = this.constructor.name;
    if(con == 'String')             return this;
    if(con == 'Arrray')             return this.toString();
    if(con == 'Object')             return JSON.stringify(this);
    if(con == 'HTMLTableElement')   return this.outerHTML;
}

包含变量的数组:

var aVar = [tab, str, ary, obj];

我循环数组以"字符串化"其内容:

for(var i in aVar){
    console.log(
        Stringify.call( aVar[i] );
    );
}

我得到了预期的字符串对象列表:

<table></table>
asdf
123,456,789
{"a":123,"b":456,"c":789}

但是,如果我想在日志中包含变量的名称,该怎么办?:

tab: <table></table>
str: asdf
ary: 123,456,789
obj: {"a":123,"b":456,"c":789}

我该怎么做?:

for(var i in aVar){
    var id = // get the name of the variable at aVar[i]
    console.log(
        id + ': ',
        Stringify.call( aVar[i] );
    );
}

这是不可能的,也没有真正的意义。您必须理解函数操作,而不是变量。

执行此操作时:

var aVar = [tab, str, ary, obj];

数组中放入的是值,而不是变量,尽管从语法上看是这样。这些值对引用它们的变量一无所知。

想想看:一个值可以被几个变量引用。获取在早些时候引用过它的变量(其中一个)的名称有什么意义?

恐怕您的用例的唯一解决方案是在执行流中携带"变量名",或者对每个变量的逻辑进行硬编码。