cdugga
cdugga

Reputation: 3859

Javascript and variable scope

I have the need to create a two dimensional array to collect values in my jsp. In order to populate the 2-d array I'm using code like this

 <script language="JavaScript">
     var row = 0;
     var multiDimenArray = new Array();
 </script>
 <c:forEach var="items" items="${item}" varStatus="status">
      ............
      <script language="JavaScript">
          multiDimenArray [row] = new Array();
          var column = 0;
          row++;
     </script>
     <c:forEach var="nestedItems" items="${nestedItem}" varStatus="status">
        ............
           <script language="JavaScript">
                multiDimenArray [row][column] = "some value";
                column++;
           </script>

However in the third script block when i attempt to assign the value i get a JS error saying that the variable row is undefined. Is it possible to pass variables between script blocks like this in JS?

Upvotes: 0

Views: 129

Answers (1)

Tim
Tim

Reputation: 5822

You are getting that because you are incrementing row before the third script runs.

So when you try to run multiDimenArray [row][column] = "some value"; row actually equals 1 instead of 0.

You need to move the row++ to after the column is assigned.

Upvotes: 2

Related Questions