0

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
2
  • Creating a JSON object that can hold all of these languages would probably work. Commented May 23, 2013 at 14:28
  • Can't you just make an array of arrays? Commented May 23, 2013 at 14:28

4 Answers 4

1
var languageNames = ['en', 'es'];
var languages = {};
for (var i = 0; i < languageNames.length; i++) {
 languages[languageNames[i]] = [];
}
answered May 23, 2013 at 14:39
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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

Comments

0

How about:

for(var i = 0; i < totalLanguages; i++){
 window["dynamicvariable " + i] = new Array();
 /*.....*/
}
answered May 23, 2013 at 14:29

2 Comments

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.
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.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.