[英]reference javascript variable through concatenation
I have few javascript variables: 我有几个JavaScript变量:
var column1
var column2
var column3
etc...
I have a for loop, 我有一个for循环,
for (i=1; i<10; i++) {}
I would like to loop through and reference these variable inside the for loop. 我想遍历并在for循环中引用这些变量。 How do I reference each column
variable individually? 如何分别引用每个column
变量? I'm looking to do something like this: 我正在寻找做这样的事情:
for (i=1; i<10; i++) {
columni = i;
}
so at the end of this I'll have: 所以到此结束,我将得到:
column1 = 1
column2 = 2
column3 = 3
You can create an object wrapper and access them that way: 您可以创建对象包装并以这种方式访问它们:
var columns = {"column1":"", "column2":"", "column3":""};
for (i=1; i<10; i++) {
columns[("column" + i)] = i;
}
columns.column1 = 1 columns.column2 = 2 columns.column3 = 3
I did something like this in jQuery, you can also use. 我在jQuery中做了类似的事情,您也可以使用。
<script type="text/javascript">
newVar = "";
for (i=1; i<10; i++) {
newVar += "var column"+i+" = "+i+";";
}
$("<script>").html(newVar).appendTo("head");
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.