Both sides previous revision
Previous revision
Next revision
|
Previous revision
|
en:web_development:tables:arrays [2021/12/10 05:25] mag [Javascript Multidimensional Arrays and Loops] |
en:web_development:tables:arrays [2023/08/16 09:33] (current) |
====== Web Development Lesson 3 - Tablas ====== | ====== Web Development Lesson 4 - Tables ====== |
===== Javascript Multidimensional Arrays ===== | ===== Javascript Multidimensional Arrays ===== |
==== Objective ==== | ==== Objective ==== |
| |
==== Setup ==== | ==== Setup ==== |
* We'll start with the work done in the previous class on [[https://jsfiddle.net]], but we'll delete all the code inside the <html><tbody></html> tag. ie. delete all the data and leave only the heading. | * In your 'project' directory, create a file called 'team.html'. |
**HTML** | * 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'. |
| * Create the table and add the header row. |
| |
| **team.html** |
<code><table> | <code><table> |
<thead> | <thead> |
</table></code> | </table></code> |
| |
**CSS** | * Copy the relevant CSS from 'style.css' in your main directory to 'style.css' in your project directory. |
| |
| **style.css** |
<code>td, th { | <code>td, th { |
border-width: 1px; | border-width: 1px; |
| |
td { | td { |
padding-left: 10px; | padding: 10px; |
padding-right: 10px; | |
padding-top: 10px; | |
padding-bottom: 10px; | |
} | } |
| |
td.age { | td.age { |
font-size: 150%; | font-size: 150%; |
| }</code> |
| |
| * Add the following code to 'team.js' so that our code only runs when the page is ready. |
| |
| **team.js** |
| <code>window.onload = function () { |
| |
}</code> | }</code> |
| |
| |
==== Arrays ==== | ==== Arrays ==== |
* Think of an array as a list. | * 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. |
* In Javascript, an array is designated by <html>[]</html> | * Each row is a list / array containing information about a single player. |
* In our example, each line (each player's data) is a list so we could represent Ospina Ramirez' data as an array. Copy this into the Javascript panel. | <code>window.onload = function () { |
<code>ospinaRemirez = ['David', 'Ospina Ramirez', 'Colombia', 33, 'Portero'];</code> | // generate player data |
* Let's take a look at this statement in detail. | player = ['David', 'Ospina Ramirez', 'Colombia', 33, 'Portero']; |
* The first word 'ospinaRemirez' is a variable named 'ospinaRemirez'. It is a place to store information. We can name variables almost anything we like, but convention is to begin with a lowercase and make the first letter of subsequent words uppercase. | }</code> |
* The <html>=</html> means we are assigning a value to the variable 'ospinaRemirez'. | |
* The first thing we see after the <html>=</html> is <html>[</html> so the value must be an array. | |
* The array contains 5 items separated by <html>,</html> and ends with <html>]</html>. | |
* Every Javascript statement must end with <html>;</html>. | |
* Now let's display the list. | * Now let's display the list. |
| <code> // create row text |
<code>statsRow = "<td>" + ospinaRamirez[0] + "</td>";</code> | statsRow = "<tr>"; |
* After creating the array, on line 2, we create a string (text) called statsRow. You can tell it's a string because of the <html>"</html> symbols. | statsRow += "<td>" + player[0] + "</td>"; |
* The string contains all the text for a data cell, but instead of writing out the player's name, we refer to the information inside the array called 'ospinaRamirez'. | statsRow += "<td>" + player[1] + "</td>"; |
* Remember that in computer progams, the first element is counted as <html>0</html>, so the name is referred to as <html>ospinaRamirez[0]</html>. | statsRow += "<td>" + player[2] + "</td>"; |
* Notice that the strings are joined by using the <html>+</html> symbol. | statsRow += "<td>" + player[3] + "</td>"; |
<code>statsRow = statsRow + "<td>" + ospinaRamirez[1] + "</td>";</code> | statsRow += "<td>" + player[4] + "</td>"; |
* In the third line, we join the new string to the old one. <html>statsRow</html> (new string) = <html>statsRow</html> (old string) + additional elements. | statsRow += "</tr>";</code> |
<code>statsRow += "<td>" + ospinaRamirez[2] + "</td>"; | * Hopefully this is familiar to you. We did something very similar when creating a list in Javascript. |
statsRow += "<td>" + ospinaRamirez[3] + "</td>"; | * We're creating a long string of code in a text variable called <html>statsRow</html>. |
statsRow += "<td>" + ospinaRamirez[4] + "</td>";</code> | * The text contains the code for a row including all the appropriate <html><tr></html> and <html><td></html> tags and the player data. |
* From the fourth line on, we simplify this to be new string <html>+=</html> additional elements, but it means the same thing. We could have written the third line the same way, but it's good to see the different options so you can choose one you like. | * <html>player[]</html> references the data in the list called 'player'. |
<code> | * Now that the string is ready we can add it to the table. |
// add row to table</code> | <code> // add row to table |
* Now, add a blank line to show we're starting something a bit different. The next line begins with <html>//</html> which means it's a comment. It tells us what the next bit of the program does, but your computer doesn't read this information. We now know that the next section of code is meant to add the row to our table. | tableBody = document.getElementsByTagName("tbody")[0]; |
<code>tableBody = document.getElementsByTagName("tbody")[0];</code> | newRow = tableBody.insertRow(0); |
* The following line shows another variable being assigned a value. The value is an element with tag name <html><tbody></html> in the document (which is our page). | newRow.innerHTML = statsRow;</code> |
* There may be more than one table (and therefore more than one <html><tbody></html> in the page, so <html>getElementsByTagName</html> returns a list and we need to identify which item in the list we want. In this case, it's the first so we use <html>[0]</html>. | * You should also recognise this code. |
* We then assign that element to a variable called <html>tableBody</html> so we can refer to it in subsequent lines of code. | * The first (after the comment) line shows the element with tag name <html><tbody></html> being assigned to the variable <html>tableBody</html>. |
<code>newRow = tableBody.insertRow(0);</code> | * Then we insert a new row at position 0 (immediately after the <html><tbody></html> tag) of our tableBody element and assign it to a variable called <html>newRow</html>. |
* Here we insert a new row at position 0 (immediately after the <html><tbody></html> tag) of our tableBody element. | * In the final line of this code, we fill our new row with <html>newRow</html> with the text string we created earlier. |
* We then assign it to a variable called <html>newRow</html> | |
<code>newRow.innerHTML = statsRow;</code> | |
* In the final line of this code, we select our new row with <html>newRow</html>. | |
* <html>.innerHTML</html> refers to the HTML code inside the element before the <html>.</html>, so we're now talking about the code inside our new row. | |
* We then use <html>=</html> so we're going to assign something to the new row. | |
* In this case, it's <html>statsRow</html> which is the string containing all the data cells. | |
* So this line pulls it all together to say 'put the string with our data into the new row of <html><tbody></html>. | |
* Let's look at the complete code so far. | * Let's look at the complete code so far. |
<code>ospinaRamirez = ['David', 'Ospina Ramirez', 'Colombia', 33, 'Portero']; | <code>window.onload = function () { |
statsRow = "<td>" + ospinaRamirez[0] + "</td>"; | // generate data |
statsRow += "<td>" + ospinaRamirez[1] + "</td>"; | player = ['David', 'Ospina Ramirez', 'Colombia', 33, 'Portero']; |
statsRow += "<td>" + ospinaRamirez[2] + "</td>"; | |
statsRow += "<td>" + ospinaRamirez[3] + "</td>"; | |
statsRow += "<td>" + ospinaRamirez[4] + "</td>"; | |
| |
// add row to table | // create row text |
tableBody = document.getElementsByTagName("tbody")[0]; | statsRow = "<tr>"; |
newRow = tableBody.insertRow(0); | statsRow += "<td>" + player[0] + "</td>"; |
newRow.innerHTML = statsRow;</code> | 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; |
| }</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 ==== |
* 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. | * 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, delete the Javascript code we made above. | * First, let's update our 'generate data' section to show an array of arrays (list of lists). |
<code> | <code> players = [ |
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>. |
* The only <html>;</html> is at the end of the entire statement. | * The only <html>;</html> is at the end of the entire statement. |
* 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> |
* It's called a loop because it will loop (iterate) through any code inside the <html>{}</html> as many times as needed. We define how many times with the structure before the <html>{</html>. | * Remember this from when you created a list using Javascript? We've replaced <html> i </html> with <html> p </html>. We're running through the code from player 1 (<html>p = 0</html>) until we reach the last player (<html>p < players.length</html>) incrementing each time (<html> p++ </html>) so we hit every player. |
* There are a few ways to do this, but we'll start with a <html>for</html> loop, using <html>p</html> as our iterator. | * Before we go any further, let's check that we have the correct information. |
* Inside the <html>()</html> we can see three code items separated by <html>;</html>. | * Add a line inside the for loop as follows. |
* The first <html>p = 0</html> tells the computer where to start - by assigning variable p a value of 0. | <code> console.log(p);</code> |
* The third says that each time the loop finishes, we should increment p (add 1). | * 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. |
* The second says to keep going while <html>p < 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 4. So the loop should run while p < 4, ie 0, 1, 2 and 3. | * 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> p </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 4 arrays, each 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's 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's 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</html> because 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])</html> calls the function <html>createRowText</html> and 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])</html> reassigns <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]] |