2014-10-05 81 views
0

我有這樣一個功能:JavaScript的轉換變量名轉換爲字符串

function testFunction(option) 
{ 
    alert(option); 
} 

(實際的功能並不僅僅是回答選項)

當然,它如果做testFunction("qwerty");工作,或testFunction(myvar);,其中myvar是一個變量。

如果我這樣做testFunction(qwerty);,它不起作用,其中qwerty不是一個變量,如預期的那樣。

我想知道是否有一種方法可以使功能檢查,以查看是否option是一個變量或字符串(如在上面的例子中"qwerty"myvar),如果它是正常繼續並提醒串或變量的值。然而,如果它不是一個變量或字符串,而是一個未定義的變量(例如上面示例中的qwerty),那麼我希望它提醒變量的名稱(在這種情況下爲qwerty)。

這可能嗎?

謝謝!


一些例子:

var myvar = "1234"; 
testFunction("test"); //alerts "test" 
testFunction(myvar); //alerts "1234" 
testFunction(qwerty); //alert "qwerty" 
+0

SO上有一個問題(接近)完全相同的標題。看到這個問題http://stackoverflow.com/questions/7983896/convert-variable-name-to-string-in-javascript – Matthias 2014-10-05 12:42:03

+0

不,這是不可能的。 – 2014-10-05 12:45:12

+0

這是什麼目的? – xShirase 2014-10-05 12:55:04

回答

1

這裏你的問題是,testFunction(QWERTY);甚至不會達到這個功能。

Javascript無法解釋變量'qwerty',因爲它沒有被定義,所以它會在那裏崩潰。

只是爲了好玩,這裏有一個方法,當你試圖解釋一個未定義的變量做你要求什麼,通過捕捉拋出的錯誤:

function testFunction(option){ 
     console.log(option); 
} 


try { 
    var myvar = "1234"; 
    testFunction("test"); //alerts "test" 
    testFunction(myvar); 
    testFunction(qwerty); //alert "qwerty" 
}catch(e){ 
    if(e.message.indexOf('is not defined')!==-1){ 
     var nd = e.message.split(' ')[0]; 
     testFunction(nd); 
    } 
} 

JSFiddle here

記住,你絕對應該從來沒有這樣做,相反,嘗試使用您的程序中的現有變量,它的效果會更好;)