I have a number of arrays with dynamic names (numbered), and I need to get first value out of each of them.
The code looks like this
var array1 = ["1","2","3"];
var array2 = ["1","2","3"];
var array3 = ["1","2","3"];
for (var cols=1; cols <=5; cols++) {
var imgs = array.cols[0];
}
I get "(index):131 Uncaught ReferenceError: arrays is not defined" in console
If your arrays are in the global scope, maybe you can access they using window
object:
var array1 = ["1","2","3"];
var array2 = ["1","2","3"];
var array3 = ["1","2","3"];
for (let i = 1; i <= 3; i++)
{
console.log(window["array" + i][0]);
}
Another, more generic, alternative is to save your arrays inside another structure, like a Map
or an Array
. I will show how yo can do it with a Map:
let array1 = ["1","2","3"];
let array2 = ["1","2","3"];
let array3 = ["1","2","3"];
let myMap = new Map([["1", array1], ["2", array2], ["3", array3]]);
myMap.forEach(([first, ...rest]) => console.log(first));
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments