0

I need to add recurrently a 2 dimensional array. The ideea is that I have a generated 2 dimensional array and I have to get the sum of all the generated arrays. I tried writing:

sum+=parseFloat(twoArray[a][b]); 

however the script is blocked and I do not get anything. it is a loop so the values of a, b float from 0 to a variable inserted by the user. I have tested the script and this is the line where it breaks.

if (k>=3){                          
    for(var i=0;i<A.length;i++){
        var smaller=new Array(A.length-1);
        for(var h=0;h<smaller.length;h++){
            smaller[h]=new Array(smaller.length);
        }
        for(var a=1;a<A.length;a++){
            for(var b=0;b<A.length;b++){
                if(b<i){
                    smaller[a-1][b]=A[a][b];
                }
                else if(b>i){
                    smaller[a-1][b-1]=A[a][b];
                }
            }   
        }
        sum+=parseFloat(smaller[a][b]);
        alert (sum);
        //dam valorile
    }
}
}
4
  • 1
    Can you add the other part of the script with an example input Commented May 21, 2012 at 16:28
  • it's a very long script. the ideea is that i have a 2 dimensional array A of k lines of k columns and I generated an array one line and one column smaller. I want to add all the resulted arrays in a sum of k-1 lines and k-1 columns. Commented May 21, 2012 at 16:32
  • obviously (after re-indentation) your array smaller has no item at [a][b], as it's length is only a-1. Could you please post the error you get when "the script breaks"? Commented May 21, 2012 at 16:49
  • the errors are at: smaller[h]=new Array(smaller.length); and sum+=parseFloat(twoArray[a][b]); Commented May 21, 2012 at 17:00

1 Answer 1

1

Put a

try {
  sum+=parseFloat(twoArray[a][b]);
} catch (e) {
   console.log(e)
}

in your loop.

So you'll see where it gets blocked and invalid inputs won't prevent the remaining summations.

Of course, I suppose you correctly checked array indexes vs lengths before.

Sign up to request clarification or add additional context in comments.

4 Comments

I have added the loop code. I have checked the generated arrays with alert and it all works fine, however it's the sum that's generating the problem.
Did you try what I suggest to check there is no exception ?
i have already checked the generated arrays and they are as they are supposed to be. the problem should be in the syntax at smaller[a][b]; if I use only smaller it works, but it takes only the first value of all the arrays.
I have tried to check and there are 2 breakpoints at: smaller[h]=new Array(smaller.length); and sum+=parseFloat(twoArray[a][b]);

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.