[英]Access the variable value using the variable name string - JavaScript
If I have: 如果我有:
var red = ["#F33121", "#F06562", "#90A4AE"]; //my array called red.
var blue = ["#345678", "#234423", "#435223"]; //my array called blue.
var color = $('.element').text(); // = red
So now, console.log(color);
所以现在, console.log(color);
returns red
. 返回red
。
How can I get 我怎样才能得到
console.log(color[0])
to return the contents of red[0]
? console.log(color[0])
返回red[0]
的内容?
Sorry if it doesn't make sense, I can't think of a simpler way to put it. 抱歉,如果没有意义,我想不出一种更简单的方法来表达它。
Bad practice: 不良做法:
If the arrays are global variables you can use bracket notation with window
object to access the array. 如果数组是全局变量,则可以对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>
Better alternative: 更好的选择:
Use the object to store the key-value pair as follow: 使用该对象来存储键值对,如下所示:
var colors = {
red: ["#F33121", "#F06562", "#90A4AE"],
blue: ["#345678", "#234423", "#435223"]
};
and access the array using 并使用访问数组
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>
If provided code is under the global context
(window), you can access property of the window
object using []
notation. 如果提供的代码在全局context
(窗口)下,则可以使用[]
表示法访问window
对象的属性。
I suggest you to have object
of arrays like var obj = {red:[...],blue:[...] }
so that you can easily access the key of the object. 我建议您使用数组object
,如var obj = {red:[...],blue:[...] }
以便您可以轻松访问该对象的键。
Try this: 尝试这个:
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`
Using object: 使用对象:
(function() { var input = { red: ["#F33121", "#F06562", "#90A4AE"], blue: ["#345678", "#234423", "#435223"] } var color = 'red' console.log(input[color][0]); })();
Change your code to be an object and you can just use bracket notation 将代码更改为对象,然后可以使用方括号表示法
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.