You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
532 lines
34 KiB
532 lines
34 KiB
<!doctype html> |
|
<html> |
|
<head> |
|
<meta charset="utf-8"> |
|
<meta http-equiv="X-UA-Compatible" content="IE=edge"> |
|
<meta name="viewport" content="width=device-width, initial-scale=1"> |
|
<title>My Learning Website</title> |
|
<link href="/styles/styles.css" rel="stylesheet" type="text/css"> |
|
<link href="/webdevelopment/styles/styles.css" rel="stylesheet" type="text/css"> |
|
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries --> |
|
<!-- WARNING: Respond.js doesn't work if you view the page via file:// --> |
|
<!--[if lt IE 9]> |
|
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> |
|
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> |
|
<![endif]--> |
|
</head> |
|
|
|
<body> |
|
|
|
<article> |
|
<h1 class="coursetitle">JavaScript Essential Training</h1> |
|
|
|
<h2 class="lecturer">LinkedIn Learning : Morten Rand-Hendriksen</h2> |
|
|
|
<h1 class="episodetitle">Working with Data</h1> |
|
|
|
<h2 class="sectiontitle">Variables: The Catch-all Containers of JavaScript</h2> |
|
|
|
<p>Variables are declared with the keyword, var. An example of this is</p> |
|
<pre><code> |
|
var a=5; |
|
</code></pre> |
|
<p>This is not actually compulsory so</p> |
|
<pre><code> |
|
a=5; |
|
</code></pre> |
|
<p>would actually work. However, you should bear in mind that any variable that you use without a var declaration will be global so that can have nasty and unexpected side-effects.</p> |
|
<p>It is worth remembering that if you create a variable in the console, you can also reference it there.</p> |
|
<img src="images/image4.png" alt="Figure 7 image"> |
|
<p class="caption">Figure 7 - using variables in the console</p> |
|
<p>In figure 7, you can see that two variables have been created, a which is equal to 5 and b which is equal to 4. We have then created another variable called sum which is equal to a + b.</p> |
|
<p>Note that when we create the first two variables, nothing is returned so we see undefined being 'returned'. When we set sum equal to a + b, 9 is returned and so we see that output and we can also see that when we type the variable name on its own, it returns itself.</p> |
|
<p>JavaScript is weakly typed, it seems to use Duck typing, like Perl. This means that you don't have to declare what type of value a variable has and you can assign different types to the same variable. That is, you might give a variable a numeric value and later assign a string value to it.</p> |
|
<p>You can also create several variables in a single line such as</p> |
|
<pre><code> |
|
var a, b; |
|
</code></pre> |
|
<p>or</p> |
|
<pre><code> |
|
var a=5, b=4; |
|
</code></pre> |
|
<p>and so on.</p> |
|
<h1 class="sectiontitle">Data Types in JavaScript</h1> |
|
<p>JavaScript has 6 data types</p> |
|
<ul> |
|
<li>Numeric</li> |
|
<li>String</li> |
|
<li>Boolean</li> |
|
<li>null</li> |
|
<li>undef</li> |
|
<li>Symbol</li> |
|
</ul> |
|
<p>The first three are very common. The fourth, null, is used occasionally. The fifth, undef, is a fallback - that is, it is what the value of a variable is if it has not yet been given a value.</p> |
|
<p>This is an important point, a variable will only have a value of null if you explicitly set the value to null. If you haven't given it a value yet, its value will be null.</p> |
|
<p>The last one, Symbol, was introduced in ECMAScript 2015 and it is not covered in this course.</p> |
|
<p>Strings can use single or double quotes and you can nest these so you might have something like this.</p> |
|
<pre><code> |
|
var string = 'There is a "quote" in this string'; |
|
</code></pre> |
|
<p>The downside here is that if you edit the string and add an apostrophe like this</p> |
|
<pre><code> |
|
var string = 'There is Fred's "quote" in this string'; |
|
</code></pre> |
|
<p>this will break the string. JavaScript will see the string as</p> |
|
<pre><code> |
|
var string = 'There is Fred' |
|
</code></pre> |
|
<p>The rest of the string would be treated as garbage. A better and safer option is to escape the quotes like this</p> |
|
<pre><code> |
|
var string = "There is a \"quote\" in this string"; |
|
</code></pre> |
|
<p>Boolean values are lower case (true, false) as is null.</p> |
|
<p>Since you can change the type of a variable, you may want to check what its type is and you can do that with the typeof function. We have a blank HTML page which we will use to demonstrate this.</p> |
|
<p>The HTML is shown in figure 8 and it uses a JavaScript file shown in figure 9.</p> |
|
<pre><code> |
|
1. <!DOCTYPE html> |
|
2. <html lang="en-US"> |
|
3. |
|
4. <head> |
|
5. <meta charset="UTF-8"> |
|
6. <meta name="viewport" content="width=device-width, initial-scale=1"> |
|
7. <title>An empty page</title> |
|
8. <script src="script.js" defer></script> |
|
9. </head> |
|
10. |
|
11. <body> |
|
12. |
|
13. </body> |
|
14. |
|
15. </html> |
|
</code></pre> |
|
<p class="caption">Figure 8 - the HTML file used to demonstrate the typeof function</p> |
|
<pre><code> |
|
1. var negInteger = -3.14159265359; |
|
2. var escQuote = "Quotes can also be \"escaped\"."; |
|
3. var theSunIsWarm = true; |
|
4. var emptyInside = null; |
|
5. var justAnotherVariable; |
|
6. |
|
7. // Try this in your console: |
|
8. // console.log(typeof insertVariableName); |
|
</code></pre> |
|
<p class="caption" >Figure 9 - the JavaScript file used to demonstrate the typeof function</p> |
|
<p>So, this displays an empty page, but the JavaScript file does declare some variables which we can use to experiment with the typeof function. In the console, we will type something like</p> |
|
<pre><code> |
|
console.log(typeof negInteger) |
|
</code></pre> |
|
<p>This will return number because negInteger holds a numeric value. Figure 10 shows the results we get with the other variables.</p> |
|
<img src="images/image5.png" alt="Figure 10 image"> |
|
<p class="caption">Figure 10 - the output we see when experimenting with using the typeof function on different data types</p> |
|
<p>The results are mostly what you might expect. Notice that the one variable we didn't give a value to, justAnotherVariable, has data type undefined.</p> |
|
<p>The most interesting results is for emptyInside which has a null value. The typeof function has identified this as an object but this is actually a mistake, the browser treats it as an object because there is literally nothing there so the browser can't really make sense of it. We can see from the code in figure 9 that it is not an object!</p> |
|
<h1 class="sectiontitle">Arithmetic Operators and Math</h1> |
|
<p>JavaScript has the usual complement of arithmetic operators including division but note that the division operator doesn't seem to perform integer division as demonstrated in figure 11.</p> |
|
<img src="images/image6.png" alt="Figure 11 image"> |
|
<p class="caption">Figure 11 - the division operator in action</p> |
|
<p>We can see here that the result of dividing 10 by 3 is 3.3333333333333335, not 3 which you would expect in a language like Java which would have performed integer division.</p> |
|
<p>This raises the question of whether JavaScript can perform modular arithmetic. Does it, for example, have a modulo operator.</p> |
|
<img src="images/image7.png"> |
|
<p class="caption">Figure 12 - demonstrating the use of the modulo operator in JavaScript</p> |
|
<p>As we can see in figure 12, JavaScript does have a modulo operator and it works as it would in, for instance Java or C.</p> |
|
<p>However, you should be aware of the fact that, unlike languages such as Java or C, the modulo operator also works on floats.</p> |
|
<img src="images/image8.png"> |
|
<p class="caption">Figure 13 - using the modulo operator with a float value</p> |
|
<p>With a float, modulo still gives you the remainder, so for instance, 4 / 1.5 would give you a result of 2.6666666666666665. 2 times 1.5 is three so the modulo operator gives a remainder of 1.</p> |
|
<p>In the other example, 3.5 / 2 would give you an answer of 1.75 so the modulo operator gives a remainder of 1.5.</p> |
|
<p>There doesn't seem to be an integer division operator in JavaScript, but there are two functions which will give you the same result and these are parseInt() and Math.floor().</p> |
|
<p>As an example, let's say we have an operation such as number = b /c where b = 10 and c = 3. We want to perform integer division to get a result of 3. We can either do the calculation like this</p> |
|
<pre><code> |
|
var number = b / c; |
|
</code></pre> |
|
<p>This will give us the whole answer rather than the integer part so we can get the integer result with</p> |
|
<pre><code> |
|
number = parseInt(number); |
|
</code></pre> |
|
<p>This gives us the integer part of the result, in this case 3. Alternatively, we can include the function in the calculation.</p> |
|
<pre><code> |
|
number = parseInt ( b / c ); |
|
</code></pre> |
|
<p>This has exactly the same effect. The Math.floor() function works in exactly the same way so we can replace parseInt() with Math.floor() in these examples to do the same thing.</p> |
|
<p>JavaScript also uses shorthand version of the arithmetic operators so, for example,</p> |
|
<pre><code> |
|
a = a + 5; |
|
</code></pre> |
|
<p>can be written as</p> |
|
<pre><code> |
|
a += 5; |
|
</code></pre> |
|
<p>The same applies for -, * and /.</p> |
|
<p>We also have an increment operators (++) and decrement operator (--) and these work as you would expect. As with Java and C, they have two forms depending on whether you want to assign a value before or after increment so, let's say a =5 and we perform the following operation.</p> |
|
<pre><code> |
|
b = a++; |
|
</code></pre> |
|
<p>As a result, b will be equal to 5 because we have assigned the value of a to b before we have incremented a. The value of a does increase to 6 as you can see in figure 14.</p> |
|
<img src="images/image9.png"> |
|
<p class="caption">Figure 14 - using the increment operator in its post-increment form</p> |
|
<p>Since the increment happens after the assignment, this is known as the post-increment operator. There is also a pre-increment operator which increments the variable before performing the assignment.</p> |
|
<pre><code> |
|
b = ++a; |
|
</code></pre> |
|
<p>This does almost the same thing but since the increment happens first, assuming an initial value of 5 for a, both a and b will then have a value of 6 and this is shown in figure 15.</p> |
|
<img src="images/image10.png"> |
|
<p class="caption">Figure 15 - using the increment operator in its pre-increment form</p> |
|
<h1 class="sectiontitle">Working with Strings and Numbers</h1> |
|
<p>In JavaScript, you can use the + operator with strings, but this is a concatenation operation, so it doesn't perform arithmetic. Assume that a = 4 and b = "5". If we perform the operation</p> |
|
<pre><code> |
|
c = a + b; |
|
</code></pre> |
|
<p>the result will be that c has a value of "45". So, a has been converted to a string and we have concatenated two strings to get the result.</p> |
|
<p>Strings don't have an equivalent of the multiplication operator, unlike some other programming languages, so if you do something like</p> |
|
<pre><code> |
|
c = a * b; |
|
</code></pre> |
|
<p>there is no operation that makes sense here, in JavaScript, if we assume that a is a string. What actually happens is that JavaScript assumes b is a number and so gives you an answer of 20.</p> |
|
<p>In this case, of course, we can convert the string to a number but this is not always possible. For example, if we change the value of b to "five" and try the same operation</p> |
|
<pre><code> |
|
c = a * b; |
|
</code></pre> |
|
<p>the result we see (in the console, at least) is NaN as shown in figure 16.</p> |
|
<img11> |
|
<p class="caption">Figure 16 - the results of multiplying a string by a number</p> |
|
<p>NaN stands for not a number and it is JavaScript's way of telling you that you have tried to perform an operation that requires the conversion of a string to a number, but the result is not valid. That is, it can convert "5" to a number but it cannot convert something like "five" or "banana" to a number. If you see the error, you might want to check to see if you have any operations involving arithmetic between a string and a number and whether that string has the value you expect.</p> |
|
<h1 class="sectiontitle">Conditional Statements and Logic</h1> |
|
<p>There isn't much that is unusual in terms of the if statement in JavaScript. Figure 17 demonstrates the JavaScript for the syntax of an if statement.</p> |
|
<pre><code> |
|
1. var a = 5; |
|
2. var b = "5"; |
|
3. var output; |
|
4. |
|
5. if (a==b) { |
|
6. output = "a and b look like the same"; |
|
7. } else if (a === b) { |
|
8. output = "a and b are defintely the same"; |
|
9. } else { |
|
10. output = "a and b are not the same"; |
|
11. } |
|
12. |
|
13. var para = document.createElement("P"); // Create a <p> element |
|
14. para.innerText = output; // Insert text |
|
15. document.body.appendChild(para); // Append <p> to <body> |
|
</code></pre> |
|
<p class="caption">Figure 17 - the syntax for an if statement in JavaScript</p> |
|
<p>We can see that in JavaScript, the if statement looks pretty similar to an if statement in many other modern programming languages and allows for both if..else and else clauses.</p> |
|
<p>Where JavaScript is different is with the comparison operators. The statement on line 5 looks like a condtion in, for example, Java so the comparison operator is ==. However, remember that JavaScript uses Duck typing so in this example, the output will be "a and b look the same". This is because a is a number and b is a string. But, if you assume that you meant to use b as a number, they are actually the same.</p> |
|
<p>We have another comparison on line 7 that uses === as the comparison operator and this will only return a true value if a and b actually do have the same value. To demonstrate this, we can amend the code so that we use the === operator first (on line 5) and the == operator on line 7.</p> |
|
<p>We will also switch lines 6 and 8 around so the if statement now looks like this. Note that these line numbers correspond to the code in figure 17, not figure 18 which only shows the if statement.</p> |
|
<pre><code> |
|
1. if (a === b) { |
|
2. output = "a and b are definitely the same"; |
|
3. } else if (a==b) { |
|
4. output = "a and b look like the same but are not exactly the same"; |
|
5. } else { |
|
6. output = "a and b are not the same"; |
|
7. } |
|
</code></pre> |
|
<p class =>Figure 18 - the same if statement as seen in figure 7 but with the order of the comparisons changed</p> |
|
<p>The reason for doing this is because we want to show that a === b returns a false value. We didn’t do that with the code in figure 17 because the first condition returned a true value so we didn't check the other conditions.</p> |
|
<p>In this case, if a === b returns a true value, this will be reflected in the output. When we save this and refresh the browser, we see the output</p> |
|
<pre><code> |
|
a and b look like the same but are definitely not the same |
|
</code></pre> |
|
<p>So, from this, we know that a === b returned a false value but a==b returned a true value. We can summarise this by saying that a === b will return a true value if the two variables or items being compared are exactly the same.</p> |
|
<p>On the other hand, a==b will also return a true value if the two variables or items being compared are exactly the same, but will also return a true value if one of the variables can be made the same as the other, for instance by assuming that a string is a number. We could summarise the possible results for different combinations of 5, "5" and "five" as shown in figure 19.</p> |
|
<table> |
|
<tr> |
|
<th>a</th> |
|
<th>b</th> |
|
<th>a == b</th> |
|
<th>a === b</th> |
|
</tr> |
|
<tr> |
|
<td>5</td> |
|
<td>5</td> |
|
<td>TRUE</td> |
|
<td>TRUE</td> |
|
</tr> |
|
<tr> |
|
<td>5</td> |
|
<td>"5"</td> |
|
<td>TRUE</td> |
|
<td>FALSE</td> |
|
</tr> |
|
<tr> |
|
<td>5</td> |
|
<td>"five"</td> |
|
<td>FALSE</td> |
|
<td>FALSE</td> |
|
</tr> |
|
</table> |
|
<p class="caption">Figure 19 - comparing the results of a==b and a===b</p> |
|
<p>We could say that == is a more permissive operator than === in that it is a little bit more flexible when deciding whether one variable has the same value as another.</p> |
|
<h1 class="sectiontitle">Advanced Conditions and Logic</h1> |
|
<p>JavaScript has logical AND and OR operators, but does not have an XOR. We can get around that by using two conditions. For example, let's imagine that we have two conditions.</p> |
|
<pre><code> |
|
(a == b) |
|
</code></pre> |
|
<p>and (not logical AND here 😊)</p> |
|
<pre><code> |
|
(c == d) |
|
</code></pre> |
|
<p>We want to execute something if either condition is true but not if both conditions are true.</p> |
|
<pre><code> |
|
1. if ( a == b || c == d ) { |
|
2. some_code; |
|
3. } |
|
</code></pre> |
|
<p class="caption">Figure 20 - a logical OR statement</p> |
|
<p>would cover the condition that at least one of them must be true, but will also execute if both conditions are true, so we want to exclude that possibility.</p> |
|
<pre><code> |
|
1. if ( ( a == b || c == d) && ( (a == b ) != ( c == d) ) { |
|
2. some_code; |
|
3. } |
|
</code></pre> |
|
<p class="caption">Figure 21 - improvising a logical OR statement in JavaScript</p> |
|
<p>This may look a little strange at first, but you should keep in mind that both ( a == b ) and ( c == d ) return Boolean values. Let's say that the Boolean value returned by ( a == b ) is x and the Boolean value returned by ( c == d ) is y.</p> |
|
<p>If x and y are both true, that is, a and b are both equal and c and d are also both equal, then the first condition in figure 21 will be true because that effectively gives us true or true. However, since both of these conditions return a true value (that is, x is equal to y), the second condition returns false. When we AND these two results, we get a false value so some_code is not executed.</p> |
|
<p>Now, let's assume that x is true but y is false. The first condition is still true because one of x and y is true. However, x does not equal y and therefore the second condition (which states that x should not equal y) is also true. As a result, the combined conditions return a true value and some_code is executed.</p> |
|
<p>Similarly, if x was false and y was true, some_code would be executed for the same reason. Hence, we can see that the code is executed if a == b is true or if c == d is true, but will not execute if both conditions are true and so we have, in effect, an XOR statement!</p> |
|
<h1 class="sectiontitle">Arrays</h1> |
|
<p>Arrays are fairly straightforward in JavaScript. You can create an array with a statement such as</p> |
|
<pre><code> |
|
var pens; |
|
</code></pre> |
|
<p>Thanks to the JavaScript method of typing, you don't need to declare it as an array, but it will become an array if you assign an array of variables to it, like this.</p> |
|
<pre><code> |
|
pens = [ "blue", "red", "green", "black"] |
|
</code></pre> |
|
<p>One side effect of this is that the elements of a JavaScript array can be of different types. For example</p> |
|
<pre><code> |
|
pens = [ "blue", 147, true, "99"] |
|
</code></pre> |
|
<p>and so on.</p> |
|
<p>Having assigned an array of variables to your array, you can then assign a different array of variables to it. Your variable name will simply point to the new array.</p> |
|
<p>You can also create an array with the array objects constructor </p> |
|
<pre><code> |
|
pens = new Array ("red", "blue", "green", "black"); |
|
</code></pre> |
|
<p>As you might expect, you can access any element using square bracket notation with the index number of the element. For example</p> |
|
<pre><code> |
|
fourth_pen = pens[3]; |
|
</code></pre> |
|
<p>and you can change an element with something like</p> |
|
<pre><code> |
|
pen[3] = "purple"; |
|
</code></pre> |
|
<p>The course video doesn't mention whether you can change the size of an array after it has been created (other than pointing it to a new array). It seems that this is possible - see <a href="https://www.samanthaming.com/tidbits/87-5-ways-to-append-item-to-array/">https://www.samanthaming.com/tidbits/87-5-ways-to-append-item-to-array/</a>.</p> |
|
<p>Actually, this will probably be covered in the next section!</p> |
|
<h1 class="sectiontitle">Properties and Methods in Arrays</h1> |
|
<p>Objects in JavaScript, including Array objects have both properties and methods.</p> |
|
<p>The file, script.js, from the exercise files demonstrates some of these methods and is shown below.</p> |
|
<pre><code> |
|
1. var pens; |
|
2. pens = ["red", "blue", "green", "orange"]; |
|
3. |
|
4. console.log("Before: ", pens); |
|
5. |
|
6. // PROPERTIES: |
|
7. Get a property of an object by name: |
|
8. console.log("Array length: ", pens.length); |
|
9. |
|
10. // METHODS: |
|
11. Reverse the array: |
|
12. pens.reverse(); |
|
13. |
|
14. // Remove the first value of the array: |
|
15. pens.shift(); |
|
16. |
|
17. // Add comma-separated list of values to the front of the array: |
|
18. pens.unshift("purple", "black"); |
|
19. |
|
20. // Remove the last value of the array: |
|
21. pens.pop(); |
|
22. |
|
23. // Add comma-separated list of values to the end of the array: |
|
24. pens.push("pink", "prussian blue"); |
|
25. |
|
26. // Find the specified position (pos) and remove n number of items from the array. Arguments: pens.splice(pos,n): |
|
27. pens.splice(pos, n) // Starts at the seccond item and removes two items. |
|
28. |
|
29. console.log("After: ", pens); |
|
30. |
|
31. // Create a copy of an array. Typically assigned to a new variable: |
|
32. var newPens = pens.slice(); |
|
33. console.log("New pens: ", newPens); |
|
34. |
|
35. // Return the first element that matches the search parameter after the specified index position. Defaults to index position 0. Arguments: pens.indexOf(search, index): |
|
36. var result = pens.indexOf(search, index); |
|
37. console.log("The search result index is: ", result); |
|
38. |
|
39. // Return the items in an array as a comma separated string. The separator argument can be used to change the comma to something else. Arguments: pens.join(separator): |
|
40. var arrayString = pens.join(separator); |
|
41. console.log("String from array: ", arrayString); |
|
42. |
|
43. // MDN documentation for Array: |
|
44. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array |
|
</code></pre> |
|
<p class="caption">Figure 22 - the script.js file used to demonstrate some of the methods for an Array object</p> |
|
<p>Note that in the course video, we are starting with everything after line 9 commented out and these will be uncommented as we look at each one in turn. I have uncommented them above to make the presentation a little nicer and to make them easier to read.</p> |
|
<h1 class="subsectiontitle">Length</h1> |
|
<p>We can get the length of an array with a statement such as</p> |
|
<pre><code> |
|
pens.length; |
|
</code></pre> |
|
<h1 class="subsectiontitle">Reverse</h1> |
|
<p>In most cases, we will use parentheses after the method name. An example of this is</p> |
|
<pre><code> |
|
pens.reverse(); |
|
</code></pre> |
|
<p>which reverses the order of the elements in the array.</p> |
|
<h1 class="subsectiontitle">Shift</h1> |
|
<p>Shift removes the first element of the array.</p> |
|
<pre><code> |
|
pens.shift(); |
|
</code></pre> |
|
<h1 class="subsectiontitle">Unshift</h1> |
|
<p>As you may expect, unshift() is the reverse of shift and adds an element at the front of the array. However, it's not completely the reverse because with unshift, you can add multiple elements with one statement.</p> |
|
<pre><code> |
|
pens.unshift("purple", "black"); |
|
</code></pre> |
|
<h1 class="subsectiontitle">Pop</h1> |
|
<p>Pop removes an element from the end of the array.</p> |
|
<pre><code> |
|
pens.pop(); |
|
</code></pre> |
|
<h1 class="subsectiontitle">Push</h1> |
|
<p>Push adds one or more elements to the end of the array.</p> |
|
<pre><code> |
|
pens.push(); |
|
</code></pre> |
|
<h1 class="subsectiontitle">Splice</h1> |
|
<p>Splice is similar to shift or pop, but it removes elements (one or more) from inside the array. Actually, it would probably be more accurate to say that it just removes one or more consecutive elements from anywhere in the array since you could, for example, remove the first element only or the last element only. As such, splice can be used in place of either shift or pop.</p> |
|
<p>You need two arguments for splice(). The first is the index of the first item to be remove and the second is the number of items to remove.</p> |
|
<p>We will demonstrate this by uncommenting as appropriate so effectively, the script becomes</p> |
|
<pre><code> |
|
1. var pens; |
|
2. pens = ["red", "blue", "green", "orange"]; |
|
3. |
|
4. console.log("Before: ", pens); |
|
5. |
|
6. // Find the specified position (pos) and remove n number of items from the array. Arguments: pens.splice(pos,n): |
|
7. pens.splice(0, 1) // Starts at the first item and removes one item. |
|
8. |
|
9. console.log("After: ", pens); |
|
</code></pre> |
|
<p class="caption">Figure 23 - demonstrating the use of splice to remove elements from an array</p> |
|
<p>Note that lines 4 and 9 output the array contents to the console in a before and after state so this is a useful technique for seeing the effect a method has on an array.</p> |
|
<p>In this example, the arguments passed to splice are 0 and 1, so we start with the first element and remove one element only. This is, in effect, emulating shift and it produces the output you can see in figure 24.</p> |
|
<img src="images/image12.png" alt="Figure 24 image"> |
|
<p class =>Figure 24 - the output we get when we use splice to emulate shift</p> |
|
<p>If we wanted to remove the last element, thereby emulating pop, we can change our splice() statement to</p> |
|
<pre><code> |
|
pens.splice(3, 1) // Starts at the fourth (last) item and removes one item. |
|
</code></pre> |
|
<p>If we wanted to remove the middle two items, we would do that with</p> |
|
<pre><code> |
|
pens.splice(1, 2) // Starts at the first item and removes one item. |
|
</code></pre> |
|
<p>Bear in mind that in each of these examples, the array is the same and has four elements. Obviously, if we removed the first element and then tried to remove the last element using an array index of 3, we would expect to see an error since we are trying to remove an error from beyond the end of the array.</p> |
|
<p>In fact, we don't get an error but the command has no effect.</p> |
|
<p>If we want to guard against this, rather than use 3 as an index element, we could create a variable to hold the position of the last element, like this</p> |
|
<pre><code> |
|
var last = pens.length-1; |
|
</code></pre> |
|
<p>We can then use this in the splice command, which becomes</p> |
|
<pre><code> |
|
pens.splice(last, 1) |
|
</code></pre> |
|
<p>So, this is safer and it will work (that is, both the first and last elements will be removed) provided that you have at least two elements in the array to begin with.</p> |
|
<p>You can also add further safeguards by, for example, checking that the array contains at least one element before each operation. Similarly, if you are using splice to remove elements from inside the array, you can check the length of the array to ensure that there are enough elements for you to remove, bearing in mind that this may have to be a higher number. For example, if we go back to the example where we removed the middle two elements</p> |
|
<pre><code> |
|
pens.splice(1, 2) // Starts at the second item and removes one item. |
|
</code></pre> |
|
<p>since we are effectively ignoring the first element, this will only work correctly if there are at least three elements in the array. Essentially, the number of elements must be the sum of the two arguments.</p> |
|
<p>That is, we start at index position 1, so we are ignoring the element at position 0. So we are ignoring one element. Because the first element is at index position 0, the number of elements we are ignoring is equal to the index of the first element to be removed (if we started at index 2, we are ignoring 1 and 0 and so on).</p> |
|
<p>So, the total number of elements that must be in the array for your splice statement to work correctly is the number of elements you are ignoring (or the index of the first element to be removed) and the number of elements you want to remove.</p> |
|
<p>Note, if you try to remove more elements than can be removed, the result will be that the splice statement will start at the given index position (assuming there is an element at that position) and remove everything to the end of the array.</p> |
|
<p>As an example, let's say we have our array with four elements, and we try to do the following</p> |
|
<pre><code> |
|
pens.splice(1, 4) // Starts at the second item and removes four items. |
|
</code></pre> |
|
<p>The result is shown below</p> |
|
<img src="images/image13.png" alt="Figure 25 image"> |
|
<p class="caption">Figure 25 - the result when we try to use splice to remove more items than are available to be removed</p> |
|
<p>So, as you can see, we have ignored the first element as specified by splice. This means that there are three remaining elements and we have tried to remove 4 of these. The result is that only the elements we chose to skip over have been left in the array, everything else has been removed.</p> |
|
<p>I think it is important to note that in many cases, you may not be too concerned about removing the wrong elements, but if there are elements of the array that you shouldn't remove, you should be careful about using a command such as splice (or any other command that removes elements from an array) without being sure that you know what is in the array first!</p> |
|
<h1 class="subsectiontitle">Slice</h1> |
|
<p>Slice is similar to splice, but rather than remove elements from the array, it copies those elements to a new array and return this. It will take the same arguments as splice, but it differs in that splice will do nothing if you don't give it any arguments (and probably, if you only give it 1).</p> |
|
<p>If you don't give any arguments to slice, it will copy the whole array and since it is returning this array, you would probably want to create a variable to assign the new array to.</p> |
|
<p>Usage would be something like this</p> |
|
<pre><code> |
|
var newPens = pens.slice(0,1); |
|
</code></pre> |
|
<p>and if we output this new array rather than the 'after' version we have been using to show the changes in the array, we get the output shown below.</p> |
|
<img src="images/image14.png" alt="Figure 26 image"> |
|
<p class =>Figure 26 - the output we get when using slice to copy the first element of an array</p> |
|
<p>Remember that with slice, we are creating a new array that copies some or all of the elements of the old array, but it does not change the old array.</p> |
|
<h1 class="subsectiontitle">Index of</h1> |
|
<p>This simply return the index for a given element. You can give indexOf two arguments. The first is the element you want to return the index for and the second, which is an optional argument, is the index that you want to start searching from. For example, if we want to know the index value for "orange", we can find that with</p> |
|
<pre><code> |
|
pens.indexOf("orange"); |
|
</code></pre> |
|
<p>We can then output the result to the console with</p> |
|
<pre><code> |
|
console.log("The search result index is: ", result); |
|
</code></pre> |
|
<p>The result we get is 3 because "orange" is the fourth element in the array and so has an index value of 3.</p> |
|
<p>If we want to skip part of the array, we would use the second argument like this.</p> |
|
<pre><code> |
|
pens.indexOf("orange", 1); |
|
</code></pre> |
|
<p>Let's change our pens array to</p> |
|
<pre><code> |
|
pens = ["orange", "blue", "green", "orange"]; |
|
</code></pre> |
|
<p>So, we now have two elements with the value of "orange". Let's say we don't know what the position of either element in the array is, but we know that there are two and we want the index of the second element. We can use</p> |
|
<pre><code> |
|
var i=pens.indexOf("orange"); |
|
</code></pre> |
|
<p>to return the index of the first "orange" element. We can then use that to locate the second element with</p> |
|
<pre><code> |
|
var result=pens.indexOf("orange", i+1); |
|
</code></pre> |
|
<p>This gives us a result of 3 which is the index value for the second "orange" element. |
|
We have to add 1 to i because this is the index position of the first element, so we want to start searching one after that index value.</p> |
|
<h1 class="sectiontitle">Join</h1> |
|
<p>The joinarrayString function is passed to an array and takes a separator as an argument and returns that array as a separated string. The separator is in the form of a string and can be any string.</p> |
|
<p>For example, let's say the array is reverted back to</p> |
|
<pre><code> |
|
pens = ["red", "blue", "green", "orange"]; |
|
</code></pre> |
|
<p>We then pass this array to the arrayString() function.</p> |
|
<pre><code> |
|
var arrayString = pens.join(", "); |
|
</code></pre> |
|
<p>In this example, we have used a comma followed by a space as the separator, so this gives us the output shown below.</p> |
|
<img src="images/image15.png" alt="Figure 27 image"> |
|
<p class="caption">Figure 27 - the result of passing the join method to pens with a comma as the separator</p> |
|
<p>We could also use a string such as " pen, " as the separator although you may want to remember that you won't see this after the last element. In that case, your output would be</p> |
|
<img src="images/image16.png" alt="Figure 28 image"> |
|
<p class="caption">Figure 28 - the result of passing the join method to pens with " pen, " as the separator</p> |
|
<p>We can actually omit the separator in the join method and it will give you a comma separate list, but you won't get any spaces. The output would therefore look like this.</p> |
|
<img src="images/image17.png" alt="Figure 29 image"> |
|
<p class="caption">Figure 29 - the result of passing the join method to pens with the default (comma without any spacing) separator</p> |
|
<p>There are other methods available for array so it is worth checking out the documentation which you will find at <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array</a>.</p> |
|
</article> |
|
<button class="previous" onclick="window.location.href='basics.html';"> |
|
Previous Chapter - The Basics |
|
</button> |
|
<button class="next" onclick="window.location.href='functionsandobjects.html';"> |
|
Next Chapter - Functions and Objects |
|
</button> |
|
<button class="coursebutton" onclick="window.location.href='javascriptessentialtraining.html'"> |
|
Course Contents |
|
</button> |
|
<button class="webdevbutton" onclick="window.location.href='/webdevelopment/webdevelopment.html'"> |
|
Web Development Page |
|
</button> |
|
<button class="homebutton" onclick="window.location.href='/index.html'"> |
|
Home |
|
</button> |
|
</body> |
|
</html> |