简体   繁体   中英

reference javascript variable through concatenation

I have few javascript variables:

var column1
var column2
var column3
etc...

I have a for loop,

for (i=1; i<10; i++) {}

I would like to loop through and reference these variable inside the for loop. How do I reference each column variable individually? 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.

<script type="text/javascript">
    newVar = "";
    for (i=1; i<10; i++) {
      newVar += "var column"+i+" = "+i+";";
    }
    $("<script>").html(newVar).appendTo("head");
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM