Here's a pseudocode example about what I'm trying to do:
var totalLanguages = XX;
for(var i = 0; i < totalLanguages; i++){
var dynamicArray + i = new Array();
/*.....*/
}
I need to create dynamically many arrays as the value of totalLanguages which can be either number.
This is to be able to do something like this:
for(var i = 0; i < totalLanguages; i++){
var arrayLanguages["es"] = dynamicArray+i;
var arrayLanguages["en"] = dynamicArray+i;
}
Is there any way to do this?
asked May 23, 2013 at 14:25
karse23
4,1456 gold badges32 silver badges33 bronze badges
-
Creating a JSON object that can hold all of these languages would probably work.tymeJV– tymeJV2013年05月23日 14:28:37 +00:00Commented May 23, 2013 at 14:28
-
Can't you just make an array of arrays?Luan Nico– Luan Nico2013年05月23日 14:28:48 +00:00Commented May 23, 2013 at 14:28
4 Answers 4
var languageNames = ['en', 'es'];
var languages = {};
for (var i = 0; i < languageNames.length; i++) {
languages[languageNames[i]] = [];
}
answered May 23, 2013 at 14:39
james
13.4k9 gold badges50 silver badges74 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
You are basically trying to recreate an array with variable names. Just use an Array to start out!
var dynamicArray = [];
for(var i = 0; i < totalLanguages; i++) {
dynamicArray[i] = new Array();
}
answered May 23, 2013 at 14:30
epascarello
208k20 gold badges206 silver badges246 bronze badges
Comments
You can use multi-dimensional arrays:
var languagesArray = new Array(totalLanguages);
for(var i = 0; i < totalLanguages; i++) {
var innerArray = new Array();
innerArray.push("Hello");
innerArray.push("World");
languagesArray[i] = innerArray;
}
console.log(languagesArray[0][0]);
See: How can I create a two dimensional array in JavaScript?
answered May 23, 2013 at 14:30
CodingIntrigue
79k32 gold badges176 silver badges178 bronze badges
Comments
How about:
for(var i = 0; i < totalLanguages; i++){
window["dynamicvariable " + i] = new Array();
/*.....*/
}
answered May 23, 2013 at 14:29
Gabe
50.7k29 gold badges147 silver badges182 bronze badges
2 Comments
Gabe
Fine downvote it and hide, that's fine. But this is actually exactly what the OP is asking for, yea there are better ways but sometimes it's good to learn the about the window object.
james
I downvoted this because I think it's a really bad idea to pollute the global scope like this. It doesn't give any benefit over using a single object to store your dynamic variables.
lang-js