78Views3Replies

Author Options:

How do I create one array or variable after another in a loop in javascript? Answered

I am currently designing a calculator (https://www.khanacademy.org/cs/calculator/5724205359824896) and I need to create a new array every time an operator (+, - *, /, ^, etc) is pressed. I want the naming to be:

var array1[];
var array2[];
var array3[];
var array4[]... etc;

and more will be created as I add up the values inside. 

Discussions

0
None
seandogue

5 years ago

array of arrays (or even an array of hashes) ? One can create dynamically defined variables in javascript, but I tend to avoid the practice as ime it's messy... or can be (and often is) messy. YMMV

For instance, using an array of arrays allows you the direct abiltiy to append to the "master" array with new sub-arrays.

Google the bolded topics above (including the word javascript to isolate the results to that code flavor) for more involved explanations.

0
None
steveastrouk

5 years ago

better define why, before assuming the best method is they one you're asking

0
None
-max-steveastrouk

Answer 5 years ago

There is a keypad drawn out and I have already programmed in variables that return true every time a key is pressed. Initially, those variables get stored in the order that they are pressed into var "array1[];" Then my previous question, I ask how I convert whatever numbers are stored there into (what I now know of as) a 'string' of digits. ( array1[2, 3, 6, 4]; to-> 2364 )

After an operator is pressed (such as 'plus'), I need to create a new array (named array 2 perhaps?) and have all key presses get stored into it instead. Those 2 numbers will then have a operator between them and when I click "=" it calculates the result.

My code currently has a LOT of redundancy that I will need to fix with loops sooner or later, but for now I just want a working solution. I am mainly doing this to learn about programming in general. https://www.khanacademy.org/cs/calculator/5724205359824896