User Tools

Site Tools


web_design:horario:arrays

Differences

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

Link to this comparison view

Next revision
Previous revision
web_design:horario:arrays [2021/10/11 09:03]
mag created
web_design:horario:arrays [2023/08/16 09:33] (current)
Line 1: Line 1:
 ====== Web Development Lesson 3 - Tablas ====== ====== Web Development Lesson 3 - Tablas ======
 ===== Javascript Arrays and Loops ===== ===== Javascript Arrays and Loops =====
 +==== 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 ==== ==== 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.
 +**HTML**
 +<code><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></code>
 +
 +**CSS**
 +<code>td, th {
 +  border-width: 1px;
 +  border-style: solid;
 +}
 +
 +td {
 +  padding-left: 10px;
 +  padding-right: 10px;
 +  padding-top: 10px;
 +  padding-bottom: 10px;
 +}
 +
 +table {
 +  border-collapse: collapse;
 +}
 +
 +#carlos {
 +  font-style: italic;
 +}
 +
 +.age {
 +  background-color: yellow;
 +}
 +
 +#carlos .age {
 +  font-weight: 900;
 +}
 +
 +td.age {
 +  font-size: 150%;
 +}</code>
 +
 +
 +==== Arrays ====
 +  * Think of an array as a list.
 +  * In Javascript, an array is designated by <html>[]</html>
 +  * 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>ospinaRemirez = ['David', 'Ospina Ramirez', 'Colombia', 33, 'Portero'];</code>
 +  * Let's take a look at this statement in detail.
 +  * 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.
 +  * 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.
 +
 +<code>statsRow  = "<td>" + ospinaRamirez[0] + "</td>";</code>
 +  * 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.
 +  * 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'.
 +  * 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>.
 +  * Notice that the strings are joined by using the <html>+</html> symbol.
 +<code>statsRow  = statsRow + "<td>" + ospinaRamirez[1] + "</td>";</code>
 +  * 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.
 +<code>statsRow += "<td>" + ospinaRamirez[2] + "</td>";
 +statsRow += "<td>" + ospinaRamirez[3] + "</td>";
 +statsRow += "<td>" + ospinaRamirez[4] + "</td>";</code>
 +  * 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.
 +<code>
 +// add row to table</code>
 +  * 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.
 +<code>tableBody = document.getElementsByTagName("tbody")[0];</code>
 +  * 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).
 +  * 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>.
 +  * We then assign that element to a variable called <html>tableBody</html> so we can refer to it in subsequent lines of code.
 +<code>newRow    = tableBody.insertRow(0);</code>
 +  * Here we insert a new row at position 0 (immediately after the <html><tbody></html> tag) of our tableBody element.
 +  * 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.
 +<code>ospinaRamirez = ['David', 'Ospina Ramirez', 'Colombia', 33, 'Portero'];
 +statsRow  = "<td>" + ospinaRamirez[0] + "</td>";
 +statsRow += "<td>" + ospinaRamirez[1] + "</td>";
 +statsRow += "<td>" + ospinaRamirez[2] + "</td>";
 +statsRow += "<td>" + ospinaRamirez[3] + "</td>";
 +statsRow += "<td>" + ospinaRamirez[4] + "</td>";
 +
 +// 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.
 +
 +==== 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, delete the Javascript code we made above.
 +<code>
 +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']
 +          ];</code>
 +  * 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.
 +  * 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.
 +<code>// loop through all players
 +for (p = 0; p < players.length; p++) {
 +}</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>.
 +  * 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.
 +  * Inside the <html>()</html> we can see three code items separated by <html>;</html>.
 +  * The first <html>p = 0</html> 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 <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.
 +  * 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.
 +<code>  // 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>";</code>
 +  * Place this code inside the for loop between the <html>{}</html>
 +  * Finally, we can add the row to the table.
 +<code>  tableBody = document.getElementsByTagName("tbody")[0];
 +  newRow = tableBody.insertRow(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.
 +  * 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.
 +<code>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;
 +}</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.
 +
 +[[web_design:horario:exercise|Next: Ejercicio]]
web_design/horario/arrays.1633968237.txt.gz · Last modified: 2023/08/16 09:33 (external edit)