javascript 将字符串附加到变量名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8261010/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Appending string to variable name
提问by user823527
Is there a way to define variables in javascript to append them with another variable?
有没有办法在javascript中定义变量以将它们附加到另一个变量?
var card_id;
var card_links_grid+card_id;
I'd like the second variable to be appended with the information found in the first variable. For each card_id there will be a card_links_grid. I want to be able to access the card_links_grid variable for a specific card_id.
我希望第二个变量附加在第一个变量中找到的信息。对于每个 card_id,都会有一个 card_links_grid。我希望能够访问特定 card_id 的 card_links_grid 变量。
What's the right way to do that?
这样做的正确方法是什么?
回答by Quentin
The right was is to use either an array or an object, depending on if the id is going to be sequential or named.
正确的做法是使用数组或对象,具体取决于 id 是顺序的还是命名的。
var card_links_grid = {};
var card_id = "the_hanged_man";
card_links_grid[card_id] = "some value";
or
或者
var card_links_grid = [];
card_links_grid.push("some value");
Variable variables are possible, but only with some hard to maintain and debug approaches that should be avoided. Use object types designed for the data structure you want to represent.
可变变量是可能的,但只有使用一些应该避免的难以维护和调试的方法。使用为要表示的数据结构设计的对象类型。
回答by Thein Hla Maw
I also recommend to use either array or object. But if you want to try with variable variable approach, you can try like this.
我还建议使用数组或对象。但是,如果您想尝试使用可变变量方法,则可以这样尝试。
var card_id=1;
window['card_links_grid_' + card_id] = 'Marco';
document.write(window['card_links_grid_' + card_id]);
Ref: http://www.i-marco.nl/weblog/archive/2007/06/14/variable_variables_in_javascri
参考:http: //www.i-marco.nl/weblog/archive/2007/06/14/variable_variables_in_javascri
回答by Baz1nga
you could use the eval
method for the same and get away with it.. something like this
你可以使用eval
相同的方法并摆脱它..像这样
var card_id=3;
var card_links_grid1=5,card_links_grid2=6,card_links_grid3=7;
eval("card_links_grid"+card_id) //will o/p 7
P.S: If I ustood the question correctly
PS:如果我正确地使用了问题