1

I'm writing a program in which the user inputs the components of multiple vectors (math). The number of vectors and number of components varies per user. The goal is to grab the components provided by the user and store them as a string array. I can change them into numbers later. My function looks like this:

//If numVect = 2, then this function should make ary1 = ["comp", "comp"] and ary2 = ["comp", "comp"]
function calcNewVect() {
    //This stores the number of vectors the user has.
    var numVect = document.getElementById("dimension").value;

    //Goes through each of the input boxes and stores the value as a string.
    for (i = 0; i < numVect; i++) {
        var strVect = document.getElementById("vector_"+(i+1)).value;

        //Trying to declare an array with a changing name here
        var ary+i = strVect.split(", ");
    } 
}

I might be going about this wrong though.

1
  • Any time you think you need a series of variables with numbered suffixes, you should probably be using an array. Commented Apr 24, 2014 at 23:17

2 Answers 2

2

Generally (i.e. in almost any programming language) dynamically creating variable names like that is discouraged and not really possible (short of using eval). Why not just use an array?

Before your top-level loop, create an array that is to contain the strVect arrays:

function calcNewVect() {
    var vectors = [];
    var numVect = ...

Then just push into it, and use it from there:

for (i = 0; i < numVect; i++) {
    var strVect = ...;

    vectors.push(strVect.split(", "));
} 
Sign up to request clarification or add additional context in comments.

Comments

0

Well, if you want to put something in an array based on a user input, try:

    var input; //perhaps have a variable that stores 1 input at a time;
    var NewArray = []; //initialize an array, careful if its inside a function as the array will re-initialize every time the function is called.

    NewArray.push(input); //the .push() method puts things at the end of the array, 
//so if there is already an item in the Array, it would go behind the current one.

Hope This Helps!

Comments

Your Answer

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.