With javascript, is it possible to define a variable name with a different string value?
For example, I have an array called "categories" with the value ['4', '9']. I am trying to use this value with the name of a previously defined array. I have several arrays defined earlier called row1, row2, row3, etc. I am using jQuery as well.
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 the + category line [i] doesn't work, but maybe it gives you an idea of what I'm trying to do? In this case, in order to output this id value to the "row4" array, it is scrolled the first time and then "row9" a second time.
Thanks for the help!
+2
source to share
3 answers
Instead of defining multiple rows1, row2, row3, etc., why not define a single row containing 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]));
}
+4
source to share