The Math Class



JavaScript, Day 3Create a new HTML file called JS03.html.The Math ClassThe Math class allows you to perform mathematical functions. Math is not a constructor. It is similar to the Math class in C#. All properties/methods of Math can be called by using Math as an object.Examplevar x = Math.PI; // Returns PIvar y = Math.sqrt(16); // Returns the square root of 16console.log("Pi is: " + x);console.log("y is: " + y);Some Math Object MethodsMethodDescriptionabs(x)Returns the absolute value of xceil(x)Returns x, rounded upwards to the nearest integerfloor(x)Returns x, rounded downwards to the nearest integermax(x,y,z,...,n)Returns the number with the highest valuemin(x,y,z,...,n)Returns the number with the lowest valuepow(x,y)Returns the value of x to the power of yrandom()Returns a random number between 0 and 1round(x)Rounds x to the nearest integersqrt(x)Returns the square root of xSee what happens with ceil and floor when the number is negative. The behavior of these methods varies from one language to another.The Array ClassArrays in JavaScript are not typed. An array can hold objects of any type. There are three ways to create an array:console.log("");var a = new Array(10); // creates a 10-element, zero-based arrayvar b = new Array("Larry", "Moe", "Curly");var c = ["John", "Paul", "George", "Ringo"];Add the above code to a script element in your HTML. Then go to the console window (F12). Type each array variable name in the console window (one at a time) and press Enter twice. The value of the variable will be displayed in the console window, like this:a[undefined × 10]b["Larry", "Moe", "Curly"]c["John", "Paul", "George", "Ringo"]You can also write directly to the console window:console.log (a); console.log (b);console.log (c);This displays the values of the arrays within square brackets.[]["Larry", "Moe", "Curly"]["John", "Paul", "George", "Ringo"]However, if you do the following:console.log (a.toString());console.log (b.toString());console.log (c.toString());You will get the contents of each array:,,,,,,,,,Larry,Moe,CurlyJohn,Paul,George,RingoNote that the above does not work with objects.Array elements are accessed using square brackets around the subscript:console.log (b[0]);This will print out the first (0th) element in the array:LarryArrays as objectsArrays are a special kind of object. You can also treat an array as if it were an object and use the object notation to access the elements of the array.console.log(b["1"];An array in JavaScript is basically what might be called a dictionary or a map in some other languages. It is basically a collection of property/value pairs. Usually the property is a non-negative integer (array index), but it can also be a string. ExampleThe following is legal in JavaScript:console.log("");var a = [1000]; // An array constant with one element: 1000 at location 0.a[1] = 2000;a["stuff"] = 3000;a[1.5] = 4000;console.log("Array using array name only: " + a);console.log("Length of array: " + a.length);console.log("Array contents, using subscripts: ");for (i=0; i<a.length; i++) console.log (i + " --- " + a[i]);console.log("Array contents: ");for (var x in a) console.log(x + " --- " + a[x]);In the case where 1.5 is used as an array index, it is converted to a string, so it works just like the "stuff" array element.In the second version of the for loop, the property names are assigned to the variable x in order, and the property name can be used to retrieve the property value.Because arrays are objects, when you assign one array's value to another array, you are actually just creating an alias for the original array.Exampleconsole.log("");var myArray = ["one", "two", "three"];var b = myArray;b[0] = "Larry";b[1] = "Curly";b[2] = "Moe";console.log("Contents of myArray: " + myArray.toString());console.log("Contents of b: " + b.toString());All changes that were made to the array b were also made to the array myArray.Array BoundsIf you use a non-negative integer for the array subscript, even if that integer is out of the bounds of the array, you will not get an error. Instead, the size of the array will automatically be increased!console.log("");b[10]="Shemp"; console.log ("b is: " + b); //An 11-element array!console.log ("b using toString(): " + b.toString()); You should get the following output:b is: Larry,Curly,Moe,,,,,,,,Shempb using toString(): Larry,Curly,Moe,,,,,,,,ShempMultidimensional ArraysJavaScript doesn't have 2-dimensional arrays, but it has arrays of arrays, which is approximately the same thing. Exampleconsole.log("");// Create arrayvar table = new Array(10);for (var i = 0; i < table.length; i++) table[i] = new Array(10);// Initialize arrayfor (var row = 0; row < table.length; row++) for (var col = 0; col < table[row].length; col++) table[row][col] = row * 10 + col;// Print out arrayfor (var row = 0; row < table.length; row++){ var s = ''; for (var col = 0; col < table[row].length; col++) s = s + table[row][col] + " - "; console.log(s);}See what happens if you convert the whole array to a string and then print it out? Try it:console.log("Printing 2D array as a string: "); console.log(table.toString());Array methodsjoin()Converts the elements into a single string. Elements are separated by commas by default. An optional string argument can be used to specify a delimiter string. console.log("");var a = new Array("Wind","Rain","Fire");var myVar1 = a.join();????? // assigns "Wind,Rain,Fire" to myVar1var myVar2 = a.join(", ");? // assigns "Wind, Rain, Fire" to myVar2var myVar3 = a.join(" + "); // assigns "Wind + Rain + Fire" to myVar3console.log(myVar1);console.log(myVar2);console.log(myVar3);reverse()Reverses the elements of the array in place. It does not create a new array.console.log("");var myArray = ["one", "two", "three"];console.log("myArray: " + myArray);myArray.reverse();console.log("myArray reversed: " + myArray);sort()Sorts the elements of the array. A function can be optionally passed to the sort method that will provide it with the rules for comparing two array elements.Exampleconsole.log("");var a = [4, 1, 2, 3];a.sort();console.log("Sorted array: " + a.toString());This will sort the array in ascending order. ExampleBut what if you want the array sorted in descending order? You can provide your own comparison method.console.log("");var sortNum = function(x, y) { if (x>y) return -1; if (x<y) return 1; return 0;};a.sort(sortNum);console.log("Sorted array (descending): " + a.toString());ExampleWhen sorting strings, if you do a sort based on the ASCII code, all words beginning with upper-case letters will appear before all words beginning with lower-case letters. Run this:console.log("");var a = ["cat", "Dog", "bug", "Ant"];a.sort();console.log("Sorted array, case sensitive: " + a.toString());It does a true ASCII sort, but a true ASCII sort is not what we usually want. It does not do an alphabetical sort. We can fix this by sending our own compare function to the sort method:var sortStrings = function (x, y) { if (x.toString().toLowerCase() < y.toString().toLowerCase()) return -1; if (x.toString().toLowerCase() > y.toString().toLowerCase()) return 1; return 0;};a.sort(sortStrings);console.log("Sorted array, case INsensitive: " + a.toString());concat()The concat method creates and returns a new array (it does not modify the sending array). The arguments may be simple elements (separated by commas), in which case they are appended to the end of the array. They may be arrays, in which case the elements of the arrays are appended to the end of the array. Examplea= [1, 2, 3];Note that it only removes the outer set of brackets (see results of the 3rd and 4th examples below).console.log("");console.log(a.concat(4, 5));console.log(a.concat([4,5],[6,7]));console.log(a.concat(4, [5, [6, 7]]));console.log(a.concat([4, [5, [6, [ 7]]]]));console.log(a);But if we convert to a string, all brackets are removed.console.log("");console.log(a.concat(4, 5).toString());console.log(a.concat([4,5],[6,7]).toString());console.log(a.concat(4, [5, [6, 7]]).toString());console.log(a.concat([4, [5, [6, [ 7]]]]).toString());console.log(a.toString());slice()The slice method returns a slice of the array (sub-array, similar to how the substring method works for most string implementations). If two arguments are provided, the first is the starting index, and the second is the ending index. The array element at the ending index is not returned! JavaScript provides everything from the starting element up to but not including the ending element. If only one argument is provided, everything from that position to the end of the array is returned. If negative numbers are given, they are assumed to start at the end of the string for position -1, the second from the end of the string for position -2, etc.Exampleconsole.log("");a = [1, 2, 3, 4, 5];console.log("Positions 1 up to 3: " + a.slice(1,3).toString());console.log("Position 2 to the end: " + a.slice(2).toString());//Note that the first argument must be to the left of the second argument!console.log("Position -1 to -3: " + a.slice(-1, -3).toString());console.log("Position -3 to -1: " + a.slice(-3, -1).toString());console.log("Position -3 to the end: " + a.slice(-3).toString());splice()The splice() method allows you to insert elements into an array. It does change the array which invoked it. First argument: location in the array where the insertion and/or deletion is to begin. Second argument: number of elements that should be deleted. If second argument is omitted, everything from the starting position (first argument) to the end of the array is deleted, but is returned as the return value of the function. Subsequent arguments: the elements to be inserted into the array starting at the position specified by the first argument. The function always returns an array of the elements that were deleted.Exampleconsole.log("");var a = [0, 1,2,3,4,5,6,7,8];b = a.splice(4);console.log('a is: ' + a.toString());console.log(' Starting at position 4 of a, b is: ' + b.toString());b = a.splice(1,2);console.log('a is: ' + a.toString());console.log('Deleting from position 1 to 2, b is: ' + b.toString());a = [1,2,3,4,5];b = a.splice(2,0,'a','b');console.log('a is: ' + a.toString());console.log('Starting at position 2, b is: ' + b.toString());b = a.splice(2,2,[1,2],3);console.log('a is: ' + a.toString());console.log('Deleting positions 3 and 4, b is: ' + b.toString());push()/pop()The push() and pop() methods allow you to treat an array like a stack. push() appends one or more elements to the end of the array. pop() removes the last element from the end of the array.Examplevar sports = ["soccer", "baseball"];sports.push("football", "swimming");console.log(sports.toString());while (sports.length >0) console.log(sports.pop().toString());Note that if you push two elements, they are pushed in the order in which they occur in the argument list.unshift()/shift()The unshift() and shift() methods are similar to push() and pop() except that they work at the beginning of the array instead of the end. var sports = ["soccer", "baseball"];sports.unshift("football", "swimming");console.log("Array before shifting: " + sports.toString());while (sports.length > 0) console.log(sports.shift().toString());Note that if you add (unshift) two elements to the front of the array, the first item in the list becomes the first element in the new array. That is, they are not added in the order in which they appear in the argument list.FunctionsFunctions are similar to functions in Java or C#. They are identified with the keyword function. Since JavaScript is not strongly typed, there is no need to specify a return type. Also, no types are given for the arguments—just the names.Since functions must be called to be executed, they are usually called in response to some user event, like clicking on a button. <script> function greeting(name) { alert("Hello, " + name + "!"); } </script><button onclick="greeting('George');">Welcome George</button><button onclick="greeting('John');">Welcome John</button>Functions can also return a value. Note that there is no indication of the return type. ExampleUse the return statement to return the value. function sum(a,b) { return a+b; }Call the function:console.log("Calling sum, with arguments 3 and 4: " + sum(3, 4));Add the following code to your HTML:<p id="demo">x</p><script> document.getElementById("demo").innerHTML=sum(4,3);</script> The text that appears in the <p> whose id is demo will be the number 7.If a function does not return a value, its return value is the value undefined.A JavaScript CalculatorAdd the following to the body of your HTML document.<form name="calcForm" id="calcForm"><input type="text" name="display" id="display" value="0"><br><input type="button" class="button" value="1" onclick="appendDigit(1);"><input type="button" class="button" value="2" onclick="appendDigit(2);"><input type="button" class="button" value="3" onclick="appendDigit(3);"><input type="button" class="button" value="+" onclick="setOperator('+');"><br><input type="button" class="button" value="4" onclick="appendDigit(4);"><input type="button" class="button" value="5" onclick="appendDigit(5);"><input type="button" class="button" value="6" onclick="appendDigit(6);"><input type="button" class="button" value="-" onclick="setOperator('-');"><br><input type="button" class="button" value="7" onclick="appendDigit(7);"><input type="button" class="button" value="8" onclick="appendDigit(8);"><input type="button" class="button" value="9" onclick="appendDigit(9);"><input type="button" class="button" value="*" onclick="setOperator('*');"><br><input type="button" class="button" value="." onclick="appendDigit('.');"><input type="button" class="button" value="0" onclick="appendDigit(0);"><input type="button" class="button" value="=" onclick="doComputation();"><input type="button" class="button" value="/" onclick="setOperator('/');"></form>Make it pretty by adding some CSS:<style> #calcForm{ margin-left:25%; } #display{ text-align:right; font-size:30px; } .button{ background-color: lightgreen; width:75px; height:75px; font-size:30px; } </style> ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download