If I have to create n variables a_1, a_2, a_3 ... a_n, where n is determined during runtime, how will I be able to do it?
Obviously, this code won't work:
var n = prompt("Enter number of variables?");
for (i=0; i<=n; i++) {
var a_i
}
As n is given by user it is not possible to pre-determine number of variables to be created.
In other words, Is it possible to create a variable with name from another variable in JS?
T.J. Crowder
1.1m201 gold badges2k silver badges2k bronze badges
asked Jun 30, 2018 at 16:18
Abhishek Choudhary
4198 silver badges19 bronze badges
-
3why not just use an array?Mureinik– Mureinik2018年06月30日 16:19:41 +00:00Commented Jun 30, 2018 at 16:19
-
Can you explain why you need to do this? This might be a use case for a JavaScript dictionaryLucas Hendren– Lucas Hendren2018年06月30日 16:19:53 +00:00Commented Jun 30, 2018 at 16:19
-
@Mureinik i want this for matrices, and array of array is not allowed in jsAbhishek Choudhary– Abhishek Choudhary2018年06月30日 16:21:04 +00:00Commented Jun 30, 2018 at 16:21
-
1@Abhishek actually an array of arrays is indeed allowed in JavaScriptPointy– Pointy2018年06月30日 16:22:27 +00:00Commented Jun 30, 2018 at 16:22
-
2How do you want to access your variables later if you don't know their names? Use an array.alexP– alexP2018年06月30日 16:23:49 +00:00Commented Jun 30, 2018 at 16:23
1 Answer 1
Yes, like this
for (i=0; i<=n; i++) {
window['a_'+i] = undefined;
}
Sign up to request clarification or add additional context in comments.
4 Comments
vsync
that will create a global variable and not necessarily on the scope of the parent function
t.niese
This would work but your should not do that. You should keep the number of properties assigned to
window as small as possible. Use an own object instead.Abhishek Choudhary
@ManuallyOverriden I cannot understand the code at all, please explain
vsync
@Abhishek - this is just like what I told you in my comment to your question, only using a global scope (
window) instead of local scope (local object)Explore related questions
See similar questions with these tags.
lang-js