User Tools

Site Tools


en:web_development:tables:arrays

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
en:web_development:tables:arrays [2021/12/10 06:28]
mag
en:web_development:tables:arrays [2023/08/16 09:33] (current)
Line 1: Line 1:
-====== Web Development Lesson Tablas ======+====== Web Development Lesson Tables ======
 ===== Javascript Multidimensional Arrays ===== ===== Javascript Multidimensional Arrays =====
 ==== Objective ==== ==== Objective ====
Line 5: Line 5:
  
 ==== Setup ==== ==== Setup ====
-  * We'll add this as a page in our project, so create a file called 'team.html' in your 'project' directory.+  * In your 'project' directory, create a file called 'team.html'.
   * Set up the template using 'html:5' and 'link:css' in the header.   * Set up the template using 'html:5' and 'link:css' in the header.
   * Also add a Javascript file using 'script:src' and set <html>src</html> to 'team.js', then create the file 'team.js'.   * Also add a Javascript file using 'script:src' and set <html>src</html> to 'team.js', then create the file 'team.js'.
Line 114: Line 114:
 }</code> }</code>
   * That's a lot of work for just displaying one line, but we don't have to go through the same thing every time.   * That's a lot of work for just displaying one line, but we don't have to go through the same thing every time.
 +
 +==== Functions ====
 +  * We want to use the 'create row text' section multiple times (once for each player) so let's move it into its own Javascript function.
 +  * A function is a block of code that can be called by a button click or from anywhere else in the Javascript code. Remember we did this for our checklists in the previous lesson?
 +  * Add this function below the existing code.
 +<code>function createRowText() {
 +    
 +}</code>
 +  * Now move the 'create row text' block inside your new function.
 +<code>function createRowText() {
 +    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>";
 +}</code>
 +  * At this point, the function doesn't know what <html>player</html> is and the main code won't have access to <html>statsRow</html>.
 +  * Add <html>player</html> between <html>()</html> to tell the original code that we need this information.
 +  * Add a new line at the end with <html>return statsRow;</html> to pass the string back to the main code. It should now look like this.
 +<code>function createRowText(player) {
 +    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>";
 +    return statsRow;
 +}</code>
  
 ==== Multidimensional Arrays ==== ==== Multidimensional Arrays ====
Line 119: Line 150:
   * First, let's update our 'generate data' section to show an array of arrays (list of lists).   * First, let's update our 'generate data' section to show an array of arrays (list of lists).
 <code>    players = [ <code>    players = [
-              ['David', 'Ospina Ramirez', 'Colombia', 33, 'Portero'], +        ['David', 'Ospina Ramirez', 'Colombia', 33, 'Portero'], 
-              ['Carlos', 'Eccehomo Cuesta Figueroa', 'Colombia', 22, 'Defensa'], +        ['Carlos', 'Eccehomo Cuesta Figueroa', 'Colombia', 22, 'Defensa'], 
-              ['Juan Guillermo', 'Cuadrado Bello', 'Colombia', 33, 'Centrocampista'], +        ['Juan Guillermo', 'Cuadrado Bello', 'Colombia', 33, 'Centrocampista'], 
-              ['Radamel Falcao', 'García Zárate', 'Colombia', 35, 'Delantero']+        ['Radamel Falcao', 'García Zárate', 'Colombia', 35, 'Delantero']
               ];</code>               ];</code>
   * Note that each line is an element in the larger list, so we separate them by <html>,</html>.   * Note that each line is an element in the larger list, so we separate them by <html>,</html>.
Line 128: Line 159:
   * So we are saying that we have an array of arrays (list of lists) called <html>players</html>.   * So we are saying that we have an array of arrays (list of lists) called <html>players</html>.
   * We want to show each player in turn, so we need data from <html>players[0]</html>, <html>players[1]</html>, <html>players[2]</html> and <html>players[3]</html>. Rather than writing out each of these in turn, we can use a javascript loop as follows.   * We want to show each player in turn, so we need data from <html>players[0]</html>, <html>players[1]</html>, <html>players[2]</html> and <html>players[3]</html>. Rather than writing out each of these in turn, we can use a javascript loop as follows.
-<code>// loop through all players+<code>// create text
 for (p = 0; p < players.length; p++) { for (p = 0; p < players.length; p++) {
 +
 }</code> }</code>
-  *  +  * Remember this from when you created a list using Javascript? We've replaced <html> </html> with <html> </html>We're running through the code from player 1 (<html>p = 0</html>) until we reach the last player (<html>< players.length</html>) incrementing each time (<html> p++ </html>) so we hit every player
-  * Inside the <html>()</html> we can see three code items separated by <html>;</html>. +  * Before we go any further, let's check that we have the correct information. 
-  * The first <html>p = 0</html> tells the computer where to start - by assigning variable a value of 0+  * Add a line inside the for loop as follows. 
-  * The third says that each time the loop finishes, we should increment p (add 1). +<code>        console.log(p);</code> 
-  * The second says to keep going while <html>< players.length</html> is true. Recall that the element after the <html>.</html> belongs to the element before the <html>.</html>, so here <html>players.length</html> is the length of the array called players, which is 4So the loop should run while p < 4, ie 0, 1, 2 and 3.+  * This will print the value of <html> p </html> in the console, which is a tool that allows you to interact with the javascript code in the page. 
 +  * Open your 'team.html' code in Live Server, which should still just show the table header row. 
 +  * Now open your Developer Tools (click the menu in top right, then select 'More Tools' and 'Developer Tools') and switch to the 'Console' panel. 
 +  * Check that it has printed (in green) the values from 0 to 3. If not, see if you can work out why. Feel free to ask for help. 
 +  * Let's take it a step further and change <html> </html> to <html>players[p]</html> which should be the data for each player. 
 +  * Check the console again (refresh the page if you need to) and you should see arrayseach with a list of player data. That tells us that we have the correct data ready to use.
   * Now, for each player, we need to create the statsRow as for the single player.   * 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'the first item in the array, so the index is 0, hence <html>players[0]</html> is the same as ospinaRamirez+  * We already have a function that does this, so let'call it
-<code>  // create stats string +<code>        // create row text 
-  statsRow  "<td>"players[p][0] + "</td>"; +        statsRow = createRowText(players[p]);</code
-  statsRow += "<td>" + players[p][1] + "</td>"; +  * We've kept the variable name as <html>statsRow</htmlbecause it fits our code for adding to the table, but this is a different variable to the one inside the function. The one inside the function only works inside the function (its 'scope' is the function). 
-  statsRow += "<td>" + players[p][2] + "</td>"; +  <html>createRowText(players[p])</htmlcalls the function <html>createRowText</htmland provides it the data belonging to the current player as we saw in the Console. 
-  statsRow += "<td>" + players[p][3] + "</td>"; +  * If you check the page again now, you'll only be showing the last player because we're overwriting the player data every time we call the function (<html>statsRow = createRowText(players[p])</htmlreassigns <html>statsRow</html>). 
-  statsRow += "<td>" + players[p][4] + "</td>";</code+  * Let's move the 'add row to table' block of code inside the 'for loop' so we display each row when the data is ready (and before we lose it). 
-  * Place this code inside the for loop between the <html>{}</html> +<code   for (p = 0; p players.length; p++) { 
-  * Finally, we can add the row to the table. +        console.log(players[p]); 
-<code>  tableBody = document.getElementsByTagName("tbody")[0]; +        // create row text 
-  newRow = tableBody.insertRow(p); +        statsRow = createRowText(players[p]); 
-  newRow.innerHTML = statsRow;</code> + 
-  * Notice that we've changed the <html>0</html> after <html>insertRow</html> to <html>p</html>If we leave it as <html>0</html> 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.+        // add row to table 
 +        tableBody = document.getElementsByTagName("tbody")[0]; 
 +        newRow    = tableBody.insertRow(0); 
 +        newRow.innerHTML = statsRow; 
 +    }</code> 
 +  * Run the code now and you'll see that it's still not quite right. All the players are listed, but the order is backwards. 
 +  * This is because we're always adding the new row in the top slot above everything else (<html>.insertRow[0]</html>). 
 +  * We want the row number to increment at the same time as the player data. 
 +<code>        newRow    = tableBody.insertRow(p);</code> 
   * There's one last change to make. <html>tableBody</html> 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.   * There's one last change to make. <html>tableBody</html> 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.   * Our final code looks like this.
-<code>players = [ +<code>window.onload = function () { 
-  ['David', 'Ospina Ramirez', 'Colombia', 33, 'Portero'], +    // generate data 
-  ['Carlos', 'Eccehomo Cuesta Figueroa', 'Colombia', 22, 'Defensa'], +    players = [ 
-  ['Juan Guillermo', 'Cuadrado Bello', 'Colombia', 33, 'Centrocampista'], +        ['David', 'Ospina Ramirez', 'Colombia', 33, 'Portero'], 
-  ['Radamel Falcao', 'García Zárate', 'Colombia', 35, 'Delantero'+        ['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 +    tableBody = document.getElementsByTagName("tbody")[0]; 
-for (p = 0; p < players.length; p++) { + 
-  // create stats string +    // display data 
-  statsRow  = "<td>"players[p][0] + "</td>"; +    for (p = 0; p < players.length; p++) { 
-  statsRow += "<td>"players[p][1] + "</td>"; +        // console.log(players[p]); 
-  statsRow += "<td>"players[p][2] + "</td>"; +        // create row text 
-  statsRow += "<td>"players[p][3] + "</td>"; +        statsRow = createRowText(players[p]); 
-  statsRow += "<td>"players[p][4] + "</td>"; + 
-   +        // add row to table 
-  /add row to table +        newRow    = tableBody.insertRow(p); 
-  newRow = tableBody.insertRow(p)+        newRow.innerHTML = statsRow; 
-  newRow.innerHTML = statsRow;+    } 
 +
 + 
 +function createRowText(player) { 
 +    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>"
 +    return statsRow;
 }</code> }</code>
-  * 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.+  * 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? What if you're using data with thousands of entries? Creating the array is much easier.
  
 [[en:web_development:tables:exercise|Next: Exercise]] [[en:web_development:tables:exercise|Next: Exercise]]
en/web_development/tables/arrays.1639146508.txt.gz · Last modified: 2023/08/16 09:33 (external edit)