2

Example, I have an array called 'categories' with the value ['4','9']. I'm trying to use that value with the name of a previously defined array. I have several arrays defined earlier called row1, row2, row3 etc. I'm also using jQuery.

Trying to do something like this:

for (i=0; i<categories.length; i++) {
    row+categories[i].push($(this).attr('id'));
    console.log(row+categories[i]);
}

Obviously row+categories[i] doesn't work, but maybe gives you an idea of what I'm trying to do? In this case to push that id value onto the array 'row4' the first time it loops through and then 'row9' the second time.

Thanks for your help!!

Joren
  • 21
  • 1
  • See: http://stackoverflow.com/questions/952457/javascript-using-variable-as-array-name and see also: http://stackoverflow.com/questions/2600420/how-to-write-this-javascript-code-without-eval and http://stackoverflow.com/questions/598878/how-can-i-access-local-scope-dynamically-in-javascript – Shog9 Apr 09 '10 at 16:56

3 Answers3

4

Rather than defining multiple row1, row2, row3 etc., why not define a single rows variable that contains multiple arrays?

var rows = [[], [], []];
var categories = ['4', '9'];
for (i = 0; i < categories.length; i++) {
    rows[categories[i]].push($(this).attr('id'));
    console.log(rows[categories[i]]);
}

It could even be an object with properties if that makes sense in your situation:

var rows = {
    row1: [],
    row2: [],
    row3: [],
    getRow: function(index) {
        return this["row" + index];
    }
    };
var categories = ['4', '9'];
for (i = 0; i < categories.length; i++) {
    rows.getRow(categories[i]).push($(this).attr('id'));
    console.log(rows.getRow(categories[i]));
}
roryf
  • 29,592
  • 16
  • 81
  • 103
0

You can use eval(), even if i don't like it personnaly...

for (i=0; i<categories.length; i++) {
    eval("row" + categories[i] + ".push($(this).attr('id'))");
    console.log(eval("row" + categories[i]));
}
Mikushi
  • 3,311
  • 4
  • 19
  • 22
0

do you want a global or local variable? (the code below uses global variables)

var rowVar;
for (i=0; i<categories.length; i++) {
  rowVar = "row"+categories[i];
  window[rowVar].push($(this).attr('id'));
  console.log(window[rowVar]);
}
scunliffe
  • 62,582
  • 25
  • 126
  • 161