gpt4 book ai didi

javascript - 使用变量名称字符串访问变量值 - JavaScript

转载 作者:行者123 更新时间:2023-12-02 15:00:18 29 4
gpt4 key购买 nike

如果我有:

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]的内容?

抱歉,如果没有意义,我想不出更简单的表达方式。

最佳答案

不良做法:

如果数组是全局变量,您可以使用 bracket notationwindow 对象来访问数组。

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>

关于javascript - 使用变量名称字符串访问变量值 - JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35472880/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com