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
1
  • you could use eval.................. but you're probably better off with @brso05's answer Commented Feb 16, 2016 at 17:01

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

2 Comments

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.
@BrianPowell an alternative if your variables are global is this: stackoverflow.com/a/1920939/4028085
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>

1 Comment

Perfect. I already rewrote this using the answer I accepted, but this actually answers my question perfectly as well. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.