需要帮助声明具有不同名称的数组,JavaScript

时间:2014-04-24 23:11:39

标签: javascript

我正在编写一个程序,其中用户输入多个向量的组件(数学)。向量的数量和组件的数量因用户而异。目标是获取用户提供的组件并将它们存储为字符串数组。我可以稍后将它们改成数字。我的功能如下:

//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(", ");
    } 
}

我可能会犯这个错误。

2 个答案:

答案 0 :(得分:2)

通常(即几乎任何编程语言)动态创建这样的变量名称是不鼓励的,并且实际上不可能(不使用eval)。为什么不使用数组?

在顶级循环之前,创建一个包含strVect数组的数组:

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

然后只需按下它,然后从那里使用它:

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

    vectors.push(strVect.split(", "));
} 

答案 1 :(得分:0)

好吧,如果您想根据用户输入在数组中添加内容,请尝试:

    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.

希望这有帮助!