User Tools

Site Tools


en:web_development:tables:arrays

This is an old revision of the document!


Web Development Lesson 3 - Tablas

Javascript Multidimensional Arrays

Objective

We'll continue building our table of stats on the Colombia team, but we'll do it more efficiently with javascript by using arrays and loops.

Setup

  • We'll add this as a page in our project, so create a file called 'team.html' in your 'project' directory.
  • Set up the template using 'html:5' and 'link:css' in the header.
  • Also add a Javascript file using 'script:src' and set src to 'team.js', then create the file 'team.js'.
  • Create the table and add the header row.

team.html

<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Surname</th>
      <th>Nationality</th>
      <th class="age">Age</th>
      <th>Position</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>
  • Copy the relevant CSS from 'style.css' in your main directory to 'style.css' in your project directory.

style.css

td, th {
  border-width: 1px;
  border-style: solid;
}

td {
  padding: 10px;
}

table {
  border-collapse: collapse;
}

#carlos {
  font-style: italic;
}

.age {
  background-color: yellow;
}

#carlos .age {
  font-weight: 900;
}

td.age {
  font-size: 150%;
}
  • Add the following code to 'team.js' so that our code only runs when the page is ready.

team.js

window.onload = function () {

}

Arrays

  • Just as a list can be represented by an array in Javascript, a table (which is a list of lists) can be represented as an array of arrays. First let's set up a single row.
  • Each row is a list / array containing information about a single player.
window.onload = function () {
    // generate player data
    player = ['David', 'Ospina Ramirez', 'Colombia', 33, 'Portero'];
}
  • Now let's display the list.
    // create row text
    statsRow  = "<tr>";
    statsRow += "<td>" + player[0] + "</td>";
    statsRow += "<td>" + player[1] + "</td>";
    statsRow += "<td>" + player[2] + "</td>";
    statsRow += "<td>" + player[3] + "</td>";
    statsRow += "<td>" + player[4] + "</td>";
    statsRow += "</tr>";
  • Hopefully this is familiar to you. We did something very similar when creating a list in Javascript.
  • We're creating a long string of code in a text variable called statsRow.
  • The text contains the code for a row including all the appropriate <tr> and <td> tags and the player data.
  • player[] references the data in the list called 'player'.
  • Now that the string is ready we can add it to the table.
    // add row to table
    tableBody = document.getElementsByTagName("tbody")[0];
    newRow    = tableBody.insertRow(0);
    newRow.innerHTML = statsRow;
  • You should also recognise this code.
  • The first (after the comment) line shows the element with tag name <tbody> being assigned to the variable tableBody.
  • Then we insert a new row at position 0 (immediately after the <tbody> tag) of our tableBody element and assign it to a variable called newRow.
  • In the final line of this code, we fill our new row with newRow with the text string we created earlier.
  • Let's look at the complete code so far.
window.onload = function () {
    // generate data
    player = ['David', 'Ospina Ramirez', 'Colombia', 33, 'Portero'];

    // create row text
    statsRow  = "<tr>";
    statsRow += "<td>" + player[0] + "</td>";
    statsRow += "<td>" + player[1] + "</td>";
    statsRow += "<td>" + player[2] + "</td>";
    statsRow += "<td>" + player[3] + "</td>";
    statsRow += "<td>" + player[4] + "</td>";
    statsRow += "</tr>";

    // add row to table
    tableBody = document.getElementsByTagName("tbody")[0];
    newRow    = tableBody.insertRow(0);
    newRow.innerHTML = statsRow;
}
  • That's a lot of work for just displaying one line, but we don't have to go through the same thing every time.

Multidimensional Arrays

  • We really want our program to run through all our players. So we have a list of players each containing a list of stats. In other words, we have an array of arrays or a multidimensional array. Let's start with the data we already know.
  • First, let's update our 'generate data' section to show an array of arrays (list of lists).
    players = [
              ['David', 'Ospina Ramirez', 'Colombia', 33, 'Portero'],
              ['Carlos', 'Eccehomo Cuesta Figueroa', 'Colombia', 22, 'Defensa'],
              ['Juan Guillermo', 'Cuadrado Bello', 'Colombia', 33, 'Centrocampista'],
              ['Radamel Falcao', 'García Zárate', 'Colombia', 35, 'Delantero']
              ];
  • Note that each line is an element in the larger list, so we separate them by ,.
  • The only ; is at the end of the entire statement.
  • So we are saying that we have an array of arrays (list of lists) called players.
  • We want to show each player in turn, so we need data from players[0], players[1], players[2] and players[3]. Rather than writing out each of these in turn, we can use a javascript loop as follows.
// loop through all players
for (p = 0; p < players.length; p++) {
}
  • Inside the () we can see three code items separated by ;.
  • The first p = 0 tells the computer where to start - by assigning variable p a value of 0.
  • The third says that each time the loop finishes, we should increment p (add 1).
  • The second says to keep going while p < players.length is true. Recall that the element after the . belongs to the element before the ., so here players.length is the length of the array called players, which is 4. So the loop should run while p < 4, ie 0, 1, 2 and 3.
  • Now, for each player, we need to create the statsRow as for the single player.
  • We no longer have the variable called ospinaRamirez, so we have to find the right line in the players array. It's the first item in the array, so the index is 0, hence players[0] is the same as ospinaRamirez.
  // create stats string
  statsRow  = "<td>" + players[p][0] + "</td>";
  statsRow += "<td>" + players[p][1] + "</td>";
  statsRow += "<td>" + players[p][2] + "</td>";
  statsRow += "<td>" + players[p][3] + "</td>";
  statsRow += "<td>" + players[p][4] + "</td>";
  • Place this code inside the for loop between the {}
  • Finally, we can add the row to the table.
  tableBody = document.getElementsByTagName("tbody")[0];
  newRow = tableBody.insertRow(p);
  newRow.innerHTML = statsRow;
  • Notice that we've changed the 0 after insertRow to p. If we leave it as 0 we'll be adding the new line at the top each time. By putting it as the index of the player in the list, the list on screen will be the same as the list in our array.
  • There's one last change to make. tableBody doesn't ever change, so there's no need to reassign it every time we go through the loop. Let's move that line above the loop so it's calculated first and never again.
  • Our final code looks like this.
players = [
  ['David', 'Ospina Ramirez', 'Colombia', 33, 'Portero'],
  ['Carlos', 'Eccehomo Cuesta Figueroa', 'Colombia', 22, 'Defensa'],
  ['Juan Guillermo', 'Cuadrado Bello', 'Colombia', 33, 'Centrocampista'],
  ['Radamel Falcao', 'García Zárate', 'Colombia', 35, 'Delantero']
          ];
          
tableBody = document.getElementsByTagName("tbody")[0];

// loop through all players
for (p = 0; p < players.length; p++) {
  // create stats string
  statsRow  = "<td>" + players[p][0] + "</td>";
  statsRow += "<td>" + players[p][1] + "</td>";
  statsRow += "<td>" + players[p][2] + "</td>";
  statsRow += "<td>" + players[p][3] + "</td>";
  statsRow += "<td>" + players[p][4] + "</td>";
  
  // add row to table
  newRow = tableBody.insertRow(p);
  newRow.innerHTML = statsRow;
}
  • This looks a lot more efficient now, but you still might think that it's easier to create the table in HTML than Javascript. Ok. What about if we use the full team? Can you imagine building the table with 26 players? Creating the array is much easier.

Next: Exercise

en/web_development/tables/arrays.1639146508.txt.gz · Last modified: 2023/08/16 09:33 (external edit)