Advanced Web Programming (Chapter 9) PDF

Summary

This document is a chapter from a course on advanced web programming. It focuses on JavaScript arrays and numbers, including how to perform common tasks, numerical values, and the Math object.

Full Transcript

Advanced Web Programming Chapter 9: ARRAYS, NUMBERS IN THIS CHAPTER Use arrays to handle lists of data Learn how to perform common tasks using the various Array properties Make sense of numbers Learn about the variety of numerical values you will encounter Meet the Math object A...

Advanced Web Programming Chapter 9: ARRAYS, NUMBERS IN THIS CHAPTER Use arrays to handle lists of data Learn how to perform common tasks using the various Array properties Make sense of numbers Learn about the variety of numerical values you will encounter Meet the Math object Arrays Let’s imagine you are writing down a list on a piece of paper. Let’s call the piece of paper “groceries.” Now, on this sheet of paper, you write a numbered list starting with zero with all the items that belong there such as what you see in the figure. By simply creating a list of things, what you have right now is a real- world example of an array! The piece of paper called “groceries” would be your array. The items that you need to purchase are known as array values (or array elements). Creating an Array To create arrays, use an open and close bracket. The example that follows is our groceries variable that is initialized to an empty array: var groceries = []; You have your variable name on the left, and you have a pair of brackets on the right that initializes this variable as an empty array. This bracket-y approach for creating an array is better known as the array literal notation. To create non-empty arrays, place the items you want inside the brackets and separate them by commas: var groceries = ["Milk", "Eggs", "Frosted Flakes", "Salami", "Juice"]; Accessing Array Values Inside an array, each item is assigned a number (index value) starting with zero. In the above example, Milk would have an index value of 0, Eggs would have an index value of 1, Frosted Flakes the index value of 2, and so on. Let’s say that our groceries array is declared as follows: var groceries = ["Milk", "Eggs", "Frosted Flakes", "Salami", "Juice"]; If we wanted to access an item from the array, all we need to do is specify the index value of the item we are interested in: groceries; The index value is specified using square brackets. In this example, you are referring to the Eggs value because the index value 1 refers to it. If you specified a 2, you would return Frosted Flakes. You can keep specifying a larger index value until you have no more entries in the array left that map to it. The number you can use as your index value goes all the way from 0 to one less than your array’s length. The reason is that, as shown in the diagram earlier, your index values start with a value of 0. If your array only has 5 items, trying to display grocery or grocery will result in a message of undefined. Accessing Array Values (Cont…) In most real-world scenarios, you will want to programmatically go through an array as opposed to accessing each item individually. we can take what we explained in the previous paragraph and use a for loop to accomplish this: for (var i = 0; i < groceries.length; i++) { var item = groceries[i]; } Notice the range of your loop starts at 0 and ends just one before your array’s full length (as returned by the length property). This works because your array index values go from 0 to one short of the value returned for the array’s length. The length property returns a count of all the items in your array. (To be precise, the length property returns the number of index values in your array, and that can sometimes not equal the number of actual items your array is storing. Adding Items to Your Array Rarely will you leave your array in the state you initialized it in originally. You will want to add items to it. To add items to your array, you will use the push method: groceries.push("Cookies"); For example, after running the code on our initial array, you will see Cookies added to the end of your groceries array as shown in Figure 14.3. Adding Items to Your Array If you want to add data to the beginning of your array, you use the unshift method: groceries.unshift("Bananas"); When data is added to the beginning of your array, the index value for all of the existing items increases to account for the newly inserted data as shown in Figure 14.4. Both the push and unshift methods, besides adding the elements to the array when you use them, return the new length of the array as well: alert(groceries.push("Cookies")); // returns 6 Removing Items from the Array To remove an item from the array, you can use the pop or shift methods. - The pop method removes the last item from the array and returns it: var lastItem = groceries.pop(); - The shift method does the same thing on the opposite end of the array. Instead of the last item being removed and returned, the shift method removes and returns the first item from the array: var firstItem =groceries.shift(); When an item is removed from the beginning of the array, the index position of all remaining elements is decremented by 1 to fill in the gap Removing Items from the Array (Cont…) When you are adding items to your array using unshift or push, the returned value from that method call is the new length of your array. That is not what happens when you call the pop and shift methods, though! When you are removing items using shift and pop, the value returned by the method call is the removed item itself! The last method we are going to look at is slice: var newArray = groceries.slice(1, 4); The slice method allows you copy a portion of an array and return a new array with just those copied items. In this extract, we copy all items between the second and fifth items in our array and return them to a new array we call…newArray! When you are using slice, your original array is just copied over. Finding Items in the Array Two built-in methods to find items in an array:indexOf and lastIndexOf. These methods work by scanning your array and returning the index position of the matching element. The indexOf method returns the index value of the first occurrence of the item you are searching for: var groceries = ["milk", "eggs", "frosted flakes", "salami", "juice"]; var resultIndex = groceries.indexOf("eggs", 0); alert(resultIndex); // 1 Notice that the resultIndex variable stores the result of calling indexOf on our groceries array. To use indexOf, we pass in the element we are looking for along with the index position to start from: groceries.indexOf("eggs", 0); The value returned by indexOf in this case will be 1. The lastIndexOf method is similar to indexOf in how you use it, but it differs a bit on what it returns when an element is found. Where indexOf finds the first occurrence of the element you are searching for, lastIndexOf finds the last occurrence of the element you are searching for and returns that element’s index position. When you search for an element that does not exist in your array, both indexOf and lastIndexOf return a value of −1. Merging Arrays The last thing we are going to do is look at how to create a new array that is made up of two separate arrays. Let’s say you have two arrays called good and bad: var good = ["Mario", "Luigi", "Kirby", "Yoshi"]; var bad = ["Bowser", "Koopa Troopa", "Goomba"]; To combine both of these arrays into one array, use the concat method on the array you want to make bigger and pass the array you want to merge into it as the argument. What will get returned is a new array whose contents are both good and bad: var goodAndBad = good.concat(bad); alert(goodAndBad); In this example, because the concat method returns a new array, the goodAndBad variable ends up becoming an array that stores the results of our concatenation operation. The order of the elements inside goodAndBad is good first and bad second: NUMBERS - Using a Number A simple example of declaring a variable called stooges that is initialized to the number 3: var stooges = 3; Using complex numbers: var pi = 3.14159; var color = 0xFF; var massOfEarth = 5.9742e+24; To use negative numbers, just place a minus (-) character before the number you want to turn into a negative value: var temperature = −42; Operators - Doing Simple Math In JavaScript, you can create simple mathematical expressions using the +, -, *, /, and % operators to add, subtract, multiply, divide, and find the remainder (modulus) of numbers respectively. If you can use a calculator, you can do simple math in JavaScript. Here are some examples that put these operators to use: var total = 4 + 26; var average = total / 2; var doublePi = 2 * 3.14159; var removeItem = 50–25; var remainder = total % 7; var more = (1 + average * 10) / 5; In the last line in the above example, notice that we are defining a particular order of operations by using parentheses around the expression we want to evaluate as a group. JavaScript evaluates expressions in the following order: 1. Parenthesis, 2. Exponents, 3. Multiply, 4. Divide, 5. Add, 6. Subtract Incrementing and Decrementing A common thing you will do with numbers involves incrementing or decrementing a variable by a certain amount. Below is an example of incrementing the variable i by 1: var i = 4; i = i + 1; You don’t have to increment or decrement by just 1. You can use any arbitrary number: var i = 100; i = i - 2; All of this doesn’t just have to just be addition or subtraction. You can perform other operations as well: var i = 40; i = i / 2; You should start to see a pattern here. Regardless of what operator you are using, you’ll notice that you are cumulatively modifying your i variable. Because of how frequently you will use this pattern, you have some operators that simplify this a bit (see Table 15.1). Incrementing and Decrementing (Cont…) One thing you should be aware of. It has to do with the -- and ++ operators for incrementing or decrementing a value by 1. Whether the ++ and -- operators appear before or after the variable they are incrementing matters. Let’s look at this example: var i = 4; var j = i++; After executing these two lines, the value of i will be 5…just like you would expect. The value of j will be 4. Notice that in this example, the operator appears after the variable. If we place the operator in front of the variable, the results are a bit different: var i = 4; var j = ++i; The value of i will still be 5. The value of j will also be 5. What changed between these two examples is the position of the operator. The position of the operator determines whether the incremented value or the preincremented value will be returned. Special Values—Infinity and NaN Infinity You can use the Infinity and -Infinity values to define infinitely large or small numbers: var reallyBigNumber = Infinity; var reallySmallNumber = -Infinity; The chances of you having to use Infinity are often very rare. Instead, you will probably see it returned as part of something else your code does. For example, you will see Infinity returned if you divide by 0. NaN The NaN keyword stands for “Not a Number”, and it gets returned when you do some numerical operation that is invalid. For example, NaN gets returned in the following case: var oops = Math.sqrt(-1); The reason is that you cannot have a square root for a negative number. The Math Object Numbers are used in a variety of mathematical expressions, and they often go beyond simple addition, subtraction, multiplication, and division. To help you more easily do complicated numerical things, you have the Math object. This object provides you with a lot of functions and constants that will come in handy, and we are going to very briefly look at some of the things this object does. The Constants Math object defines many common constants for you, The most used constant is Math.PI: Here is an example of a function that returns the circumference given the radius: function getCircumference(radius) { return 2 * Math.PI * radius; } alert(getCircumference(2)); Rounding Numbers Your numbers will often end up containing a ridiculous amount of precision: var position = getPositionFromCursor(); //159.3634493939 To help you round these numbers up to a reasonable integer value, you have the Math.round(), Math.ceil(), and Math.floor() functions that take a number as an argument. The easiest way to make sense of the table is to just see these three functions in action: Math.floor(.5); // 0 Math.ceil(.5); // 1 Math.round(.5); // 1 Math.floor(3.14); // 3 Math.round(3.14); // 3 Math.ceil(3.14); // 4 Math.floor(5.9); // 5 Math.round(5.9); // 6 Math.ceil(5.9); // 6 Trigonometric Functions The Math object gives you handy access to almost all of the trigonometric functions you will need. To use any of these, just pass in a number as the argument: Math.cos(0); // 1 Math.sin(0); // 0 Math.tan(Math.PI / 4); // 0.9999999999999999 Math.cos(Math.PI); // -1 Math.cos(4 * Math.PI); // 1 These trigonometric functions take arguments in the form of radian values. If your numbers are in the form of degrees, be sure to convert them to radians first. Powers and Square Roots Continuing down the path of defining the Math object functions, we have Math. pow() Math.exp() and Math.sqrt() Let’s look at some examples: Math.pow(2,4)//equivalent of 2^4 (or 2 * 2 * 2 * 2) Math.exp(3) //equivalent of Math.E^3 Math.sqrt(16) //4 Note that Math.pow() takes two arguments. Getting the Absolute Value If you want the absolute value of a number, simply use the Math.abs()function: Math.abs(37) //37 Math.abs(-6) //6 If you pass in a negative number, it returns the positive variant of it. Random Numbers To generate a somewhat random number between 0 and a less than 1, you have the Math.random() function. This function doesn’t take any arguments, but you can simply use it as part of a mathematical expression: var randomNumber = Math.random() * 100; Each time your Math.random function is called, you will see a different number returned for Math.random(). Lab https://www.w3schools.com/js/js_arrays.asp https://www.w3schools.com/js/js_array_methods.asp https://www.w3schools.com/js/js_numbers.asp https://www.w3schools.com/js/js_math.asp https://www.w3schools.com/js/js_random.asp

Use Quizgecko on...
Browser
Browser