In javascript I have an array of strings in which each string is name of another array.
How can I get each array object from its name?
In my example I need to get cavaSel array from its name which is contained in array CaveTipo
for (var i = 0; i < CaveTipo.length; i++) {
var cavaSel = $(CaveTipo[i]);
for (var t = 0; t < cavaSel.length; t++) {
///
}
}
By 'name' I'll assume you mean 'identifier'.
For example: say you have 'identifier' CaveTipo
to reference the following example array:
var CaveTipo=[ 'my_array_a'
, 'my_array_b'
, 'my_array_c'
]
; //end var
Above example array, contains strings which are the identifiers of other array's, for example:
var my_array_a=[ /* data */ ]
, my_array_b=[ /* data */ ]
, my_array_c=[ /* data */ ]
; //end var
Now in order to use the identifier (strings) in CaveTipo
one should use bracket-notation on the object that holds the target-arrays: namespace[/*identifier*/]
(instead of dot-notation).
If that namespace was global, then you'd use window
(or self
): window[/*identifier*/]
.
var cavaSel, i, t;
for (i = 0; i < CaveTipo.length; i++) {
cavaSel = window[ CaveTipo[i] ];
for (t = 0; t < cavaSel.length; t++) {
///
}
}
Now let's assume the array's are inside an object you created (in global):
var caveData={ my_array_a: [ /* data */ ]
, my_array_b: [ /* data */ ]
, my_array_c: [ /* data */ ]
}
;
var cavaSel, i, t;
for (i = 0; i < CaveTipo.length; i++) {
cavaSel = caveData[ CaveTipo[i] ];
for (t = 0; t < cavaSel.length; t++) {
///
}
}
This last approach is better in most cases since it either frees up namespace usage in global (for my_array_X
) OR provides an identifier to the object within 'private' closures.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.