简体   繁体   中英

To pass 2D Dimensional array as an argument?

When I run the below code , with data array as an local variable it was working fine. but, when I declared it as Global variable it was not working. can anybody please help me how to pass 2D dimensional array into the function.

<html>
<table>

 <tr>
  <select id="Ultra" name="letters" onchange="myFunction()">
          <option value="0">1</option>
          <option value="1">2</option>
          <option value="2">3</option>
          <option value="3">4</option>
      </select>
   </tr>
   <tr>
   <td id="demo">
   <script>
            var data = [[0,1],[1,3],[2,6]];
             function myFunction(data[][]) 
             { 

                var x = document.getElementById("Ultra").value;
                for(i=0;i<data.length;++i)
                {
                  if(data[i][0] == x)
                  {
                    var a = data[i][1];
                  }
                  document.getElementById("demo").innerHTML = a;
                }
              }


   </script>
   </td>
   </tr>

</table>
</html>

This is how to pass in a 2d array to a function. This is about as simple as I can make it. There's no need to define the type (ie don't do data[][] ) when defining the function (I think that's where you were going wrong).

// define 2d array
var data = [[0,1],[1,3],[2,6]];

// define function
function myFunction(foobar){
    // ... do something with 2d array "foobar" ...
}

// invoke function, passing in 2d array
myFunction(data);

Example: Try it out using a tool like jsbin !

You can just pass the variable directly. It will still be a 2D array inside the function:

function myFunction(array) {
    // code
}

myFunction([[1,2],[3,4]]);

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