2013-06-18 37 views
3

確定你有一組變量:在javascript中將字符串轉換爲變量名?

var height1 = 10 
var height2 = 20 
... 
var height7 = 70; 

用戶已給定的輸入,你需要讓這些變量之一的值,下面是該代碼:

if(window.location.hash) { 
     var hash = window.location.hash.substring(1); 
      var option_name = $('a[name=' + hash + ']').closest('[id^="option"]').attr("id"); 
      var hash_div_height_id = "height" + option_name.substring(6); 
      $('a[name=' + hash + ']').closest('[id^="option"]').show(); 
      $('a[name=' + hash + ']').closest('[id^="option"]').height(hash_div_height_id); 
    } else { 
     // No hash found 
    } 

我的問題現在我無法將「hash_div_height_id」(它當前代表字符串「height1」或「height2」或jQuery返回的任何數字附加到字符串末尾)傳遞給height函數,因爲它是一個字符串。

那麼我該如何去解決這個問題呢?我可以以某種方式將字符串「height1」轉換爲表示之前建立的變量height1嗎?

+2

我想你想[括號表示法](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Member_Operators#Bracket_notation)。我會看看我能否找到一個好的重複。 – apsillers

+0

我會說使用'eval',但我知道我會被閹割;) – krishgopinath

+0

重複[訪問JavaScript變量名稱的值?](http://stackoverflow.com/questions/4399794/access-value -of-javascript-variable-by-name)和[Javascript動態變量名稱](http://stackoverflow.com/questions/5117127/javascript-dynamic-variable-name) – apsillers

回答

5

指定的高度是作爲一個對象的屬性。

喜歡的東西..

var heightObj = { 
     height1 : 10, 
     height2 : 20, 
     height7 : 70 
    }; 

var hash_div_height_id = "height" + option_name.substring(6); 

要訪問的特定屬性,使用[]符號來訪問屬性

var newHeight = heightObj[hash_div_height_id]; 
$('a[name=' + hash + ']').closest('[id^="option"]').height(newHeight); 
+0

這很好用!非常感謝你@Sushanth!我真的很想在不使用eval的情況下完成這項工作,我很欣賞這種見解。 – javArc

+0

@javArc ..很高興有幫助:) –

2

假設變量在全球範圍內聲明的,你可以做window[hash]

那是因爲你在全球範圍內聲明任何變量的連接作爲prpoerty到window(假設代碼在瀏覽器中運行)。你可以通過點符號得到任何財產的價值

window.height1

或使用屬性名作爲鍵索引。也就是說

window["height1"] 

因爲你可以通過一個變量保存的關鍵,你可以簡單地做

var hash = "height1"; //replace with the code you already have 
var height = window[hash]; 
+0

感謝您對「窗口」如何運作的見解,我對此仍然比較陌生。 – javArc

+0

@javArc我們都在某一點 –

0

你有在控制變量作爲數組高度會適合你好得多,如果失敗了,請自己創建數組,以便將高度1..X推到數組上,然後可以使用索引。