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!!
-
See: stackoverflow.com/questions/952457/… and see also: stackoverflow.com/questions/2600420/… and stackoverflow.com/questions/598878/…Shog9– Shog92010年04月09日 16:56:36 +00:00Commented Apr 9, 2010 at 16:56
3 Answers 3
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]));
}
Comments
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]));
}
Comments
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]);
}