確定你有一組變量:在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嗎?
我想你想[括號表示法](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Member_Operators#Bracket_notation)。我會看看我能否找到一個好的重複。 – apsillers
我會說使用'eval',但我知道我會被閹割;) – krishgopinath
重複[訪問JavaScript變量名稱的值?](http://stackoverflow.com/questions/4399794/access-value -of-javascript-variable-by-name)和[Javascript動態變量名稱](http://stackoverflow.com/questions/5117127/javascript-dynamic-variable-name) – apsillers