-1

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?

14
  • 3
    why not just use an array? Commented Jun 30, 2018 at 16:19
  • Can you explain why you need to do this? This might be a use case for a JavaScript dictionary Commented Jun 30, 2018 at 16:19
  • @Mureinik i want this for matrices, and array of array is not allowed in js Commented Jun 30, 2018 at 16:21
  • 1
    @Abhishek actually an array of arrays is indeed allowed in JavaScript Commented Jun 30, 2018 at 16:22
  • 2
    How do you want to access your variables later if you don't know their names? Use an array. Commented Jun 30, 2018 at 16:23

1 Answer 1

-2

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

that will create a global variable and not necessarily on the scope of the parent function
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.
@ManuallyOverriden I cannot understand the code at all, please explain
@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)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.