![](/img/trans.png)
[英]Is there a way to access a javascript variable using a string that contains the name of the variable?
[英]Access the variable value using the variable name string - JavaScript
如果我有:
var red = ["#F33121", "#F06562", "#90A4AE"]; //my array called red.
var blue = ["#345678", "#234423", "#435223"]; //my array called blue.
var color = $('.element').text(); // = red
所以現在, console.log(color);
返回red
。
我怎樣才能得到
console.log(color[0])
返回red[0]
的內容?
抱歉,如果沒有意義,我想不出一種更簡單的方法來表達它。
不良做法:
如果數組是全局變量,則可以對window
對象使用括號符號來訪問數組。
window[color][0]
var red = ["#F33121", "#F06562", "#90A4AE"]; //my array called red. var blue = ["#345678", "#234423", "#435223"]; //my array called blue. $('input').on('keyup', function() { var color = $.trim($(this).val()); $('pre').html(window[color] ? JSON.stringify(window[color], 0, 4) : 'No color found'); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <input type="text" /> <pre></pre>
更好的選擇:
使用該對象來存儲鍵值對,如下所示:
var colors = {
red: ["#F33121", "#F06562", "#90A4AE"],
blue: ["#345678", "#234423", "#435223"]
};
並使用訪問數組
colors[color]
var colors = { red: ["#F33121", "#F06562", "#90A4AE"], blue: ["#345678", "#234423", "#435223"] }; $('input').on('keyup', function() { var color = $.trim($(this).val()); $('pre').html(colors[color] ? JSON.stringify(colors[color], 0, 4) : 'No color found'); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <input type="text" /> <pre></pre>
如果提供的代碼在全局context
(窗口)下,則可以使用[]
表示法訪問window
對象的屬性。
我建議您使用數組object
,如var obj = {red:[...],blue:[...] }
以便您可以輕松訪問該對象的鍵。
嘗試這個:
var red = ["#F33121", "#F06562", "#90A4AE"]; var blue = ["#345678", "#234423", "#435223"]; var color = 'red' console.log(window[color][0]);//will not work if variables are local and do not belong to `window`
使用對象:
(function() { var input = { red: ["#F33121", "#F06562", "#90A4AE"], blue: ["#345678", "#234423", "#435223"] } var color = 'red' console.log(input[color][0]); })();
將代碼更改為對象,然后可以使用方括號表示法
var colors = {
red : ["#F33121", "#F06562", "#90A4AE"],
blue : ["#345678", "#234423", "#435223"]
};
var color = $('.element').text();
console.log(colors[color]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.