如果我有:
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]
的内容?
对不起,如果没有意义,我想不出更简单的方法。
答案 0 :(得分:2)
不良做法:
如果数组是全局变量,您可以使用bracket notation和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>
答案 1 :(得分:0)
如果提供的代码位于全局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]);
})();
答案 2 :(得分:0)
将您的代码更改为对象,您只需使用括号表示法
var colors = {
red : ["#F33121", "#F06562", "#90A4AE"],
blue : ["#345678", "#234423", "#435223"]
};
var color = $('.element').text();
console.log(colors[color]);