简体   繁体   中英

Initializing JavaScript array based on user input

I have an applet that allows the user to define values for 10 variables, all of which could be arrays. I then want the program to iterate over all possible combinations and then save the calculations to a variable.

Previously I hard-coded it to initialize the result array, SIGMA, by looping over every variable, regardless of if it is a vector or a single value, IE:

SIGMA = new Array(A.length);
for (i1=0; i1<A.length; i1++) {
  SIGMA[i1] = new Array(B.length);
  for (i2=0; i2<B.length; i2++) {
    SIGMA[i1][i2] = new Array(C.length);
    for (i3=0; i3<C.length; i3++) {
      ...
    }
  }
}

This results in a 10-dimensional SIGMA array, which makes processing really slow if a few or more variables are arrays.

What I'd like to do is to have it initialize SIGMA only for those variables that are an array and not a singular value. Therefore, if all variables are a single number except for two, say X and Y, then I'd want to have:

SIGMA = new Array(X.length);
for (i1=0; i1<X.length; i1++) {
  SIGMA[i1] = new Array(Y.length);
}

However, I'm not quite sure how the best way to do this would be, as the number of for loops would depend on the number of variables that are arrays. I'm thinking I either need to use a recursive function or somehow incorporate a while loop.

Anybody have any good ideas on how this can be done? Thanks!

I was able to solve this problem by making a recursive function that included the for loops:

sigma = new Array(eval(var_idx[0]).length);
sigma_forloop('sigma', 0)

function sigma_forloop(X, idx) {
    for (var i=0; i<eval(var_idx[idx]).length; i++) {
        eval(X + '[' + i + ']' + ' = new Array(eval(var_idx[idx+1]).length);')
        if (idx+2 < var_idx.length) {
            var Y = X + '[' + i + ']';
            sigma_forloop(Y, idx+1);
        }
    }
}

The variable 'var_idx' in an array of strings containing the variables that have more than one value, therefore, it's those variables that I want to loop over.

I'm sure there's an easier way of doing it, but this works for now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM