簡體   English   中英

如何在JavaScript中檢索變量的名稱

[英]How do I retrieve the name of a variable in JavaScript

好吧,讓我們說我有各種各樣的變量:

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

盡管從語法上看,數組中放置的是值而不是變量。 這些值對引用它們的變量一無所知。

考慮一下:一個值可以由多個變量引用。 在更早的時候獲取訪問已引用它的變量之一的名稱有什么意義?

恐怕針對您的用例的唯一解決方案是在執行流程中攜帶“變量名”,或者為每個變量硬編碼您的邏輯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM