0

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
S.A.Norton Stanley
  • 1,833
  • 3
  • 23
  • 37
Brian Powell
  • 3,336
  • 4
  • 34
  • 60
  • you could use `eval`.................. but you're probably better off with @brso05's answer – sg.cc Feb 16 '16 at 17:01

2 Answers2

2

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
brso05
  • 13,142
  • 2
  • 21
  • 40
  • I thought that might be the way I had to do it. Thanks for confirming this. I just didn't want to re-write a bunch of code to put them in an object if I didn't have to. – Brian Powell Feb 16 '16 at 17:00
  • @BrianPowell an alternative if your variables are global is this: http://stackoverflow.com/a/1920939/4028085 – brso05 Feb 16 '16 at 17:02
1

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>
Niklesh Raut
  • 34,013
  • 16
  • 75
  • 109
  • Perfect. I already rewrote this using the answer I accepted, but this actually answers my question perfectly as well. Thanks! – Brian Powell Feb 16 '16 at 19:00