1 / 48

JAVASCRIPT

JAVASCRIPT. Session 2. Overview. Introduction, Data Types, Operators and Statements JS #2: JavaScript Objects, Functions The Browser, The DOM, Dynamic pages, Debugging JavaScript and Custom Object creation, Storage XML - JSON, Introduction to Ajax. Operators and Statements.

jeffreyp
Télécharger la présentation

JAVASCRIPT

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. JAVASCRIPT Session 2

  2. Overview • Introduction, Data Types, Operators and Statements • JS #2: JavaScript Objects, Functions • The Browser, The DOM, Dynamic pages, Debugging • JavaScript and Custom Object creation, Storage • XML - JSON, Introduction to Ajax

  3. Operators and Statements • Statement types • assignment • function call • conditional • loop

  4. Assignment Statement An expression consisting of a variable on the left side, an assignment operator ‘=’, and the value that is being assigned on the right. The value can be: • literal value -> x = 35.7; • variable - > x = y; • function call - > x = Math.sqrt(25);

  5. Arithmetic Operators • We just saw how a value can be assigned to a variable. The value can also be assigned using arithmetic operators. • var x = q + y; • Remember, the ‘+’ operator will behave differently if the q and y are strings as opposed to numbers. • Strings: + operator does concatenation • Numbers: + operator does addition

  6. Arithmetic Operators The arithmetic operator list: • + addition on numbers, concatenation on strings • - subtraction • * multiplication • / division • % modulus

  7. The Unary Operators There are 3 unary operators • ++ Increments a value num++; Same as: num = num + 1; • - - Decrements a value num--; Same as: num = num - 1; • - Represents a negative value FYI: num++; is not the same as ++num; • Called post-increment and pre-increment • Not important for the time being, but something to be aware of

  8. Operator Precedence • JavaScript processes some expressions containing some operators before others. • Given: aValue = 3 and bValue = 6 • var nValue = aValue + 30 / 2 - bValue * 3; • What is the value of nValue? • 3 + 30 / 2 – 6 * 3 • 3 + (30/2) – (6*3) • 0

  9. Operator Precedence • JavaScript processes some expressions containing some operators before others. • Given: aValue = 3 and bValue = 6 • var nValue = (aValue + 30) / (2 – bValue) * 3; • What is the value of nValue? • 33 / -4 * 3 • - 8.25 * 3 • - 24.75

  10. Increment Shortcut We saw earlier that num++ is the same as num = num + 1 Other operator 'shortcuts': += -= *= /= • num = num + 5; Is the same as: num += 5; • num = num -3; Is the same as: num -= 3; • num = num * 10; Is the same as: num *= 10; • num = num / 2; Is the same as: num /= 2;

  11. Conditional Statements <html> <head> <title>Conditional Example</title> <script type="text/javascript"> function choices() { var prefChoice = 1; var stateChoice = 'IL'; var genderChoice = 'M'; if(prefChoice == 1) { alert("You picked number 1"); if(stateChoice == 'IL') { alert("You picked number 1 and you are from Illinois"); if(genderChoice == 'M') { alert("You picked number 1 and you are from Illinois and are male"); } // innermost block } // middle block } // outer block } </script> </head> <body onload="choices()"> </body> </html>

  12. Conditional Statements <script type="text/javascript"> //<![CDATA[ function choices() { var prefChoice = 2; var stateChoice = 'IN'; var genderChoice = 'F'; if(prefChoice == 1) { alert("You picked number 1"); if(stateChoice == 'IL') { alert("You picked number 1 and you are from Illinois"); if(genderChoice == 'M') { alert("You picked number 1 and you are from Illinois and you're male"); } // innermost block } // middle block } else { // outer block alert("You did not pick number 1"); if(stateChoice == 'IL') { alert("You did not pick number 1 and you are from Illinois"); if(genderChoice == 'M') { alert("You picked number 1 and you are from Illinois and you're male"); } // innermost block } else { // middle block alert("You did not pick number 1 and you are not from Illinois"); if(genderChoice == 'M') { alert("You did not pick number 1 and you are not from Illinois and you're male"); } else { // innermost block alert("You did not pick number 1 and you are not from Illinois and you're female"); } } } } //]]> </script>

  13. switch Statement <html> <head> <title>Conditional Example</title> <script type="text/javascript"> function choices() { var stateChoice = 'IL'; switch(stateChoice) { case 'IN': alert("You are from Indiana"); break; case 'FL': case 'OH': case 'IL': alert("You are from Florida, Ohio or Illinois"); break; default: alert("You are from somewhere else"); break; } } </script> </head> <body onload="choices()"> </body> </html>

  14. Equality and Inequality Operators • if (nValue == ‘IL’) is not the same as if (nValue = ‘IL’) • '=' is an assignment operator (i.e. it assigns a value) • '==' is an equality operator (i.e. it compares two values and returns a boolean) • In the second example, (nValue = ‘IL’) will end up evaluating to ‘true’. The reason is that because the assignment statement is “successful”, the conditional “test” returns as true. • There is also a corresponding '!=' (inequality) operator: if (nValue != ‘IL’)

  15. “Strict” Equality and Inequality Sometimes, JavaScript tries to “help out” a little… var num = 3, str = “3”; if ( num == str )  returns true JS will attempt to do a type conversion to convert the items on either side of the equality operator so that they are of the same data type. While it is certainly possible that we wanted to compare these two items and have them be the same, in many cases, it can lead to unexpected and undesirable results. These are particularly insidious as they can show up much later down the road when the issue is considerably more difficult to nail down. With JS v 1.3 (ECMA Standard 262, edition 3), a new equality operator was introduced, ‘===‘. In addition to the evaluating the values of the two items for equality, this operator also only returns true if the data types of the items are identical. SO: (num == str )  returns true (num === str )  returns false Note: There is a corresponding !== to test for non-equality. Some programmers strongly advocate always using ‘===‘ and ‘!==‘ unless there is a specific reason for not doing so.

  16. Other Relational Operators • With the ‘==’ and ‘!=’ we were testing for equality. • Sometimes we have to test for a range, just not one specific case. • if(aValue1 > aValue2) • > greater than • < less than • >= greater than or equal • <= less than or equal

  17. Ternary Operator • SYNTAX: condition ? value if true : value is false; • This operator ultimately becomes a short-cut for a simple if/else statement. Note that this operator returns a value. A very handy shortcut! • ( 5 > 10 ) ? “hello” : “goodbye”; • Will return the string “goodbye”; • var nValue = 5.0; • var nResult = (nValue > 20) ? 1 : -1 • nResult will be assigned -1

  18. Logical Operators • if( (nValue > 10) && (nValue <= 100) && (nValue!=2) ) • Logical “and”: && • Returns true only if ALL conditionals are true • if( (nValue > 10) || (nValue <= 100) || (nValue!=0) ) • Logical “OR”: || • Returns true as long as ONE of the conditionals is true • if((nValue != null) && (nValue <= 100)) • if(!(nValue > 10))

  19. Practice: Logical Operators If nValue is assigned a value of 12, PREDICT whether the conditional will return true or false: • if( (nValue > 10) && (nValue <= 100) && (nValue != 12) ) • Returns false. First two statements are true, but third is false. Recall that with logical AND, ALL statements must be true for the whole conditional to evaluate to true. • if( (nValue < -20) || (nValue > 20) || (nValue!=0) ) • Returns true. The first two statements are false, but the third is true. Recall that with the logical ‘OR’, only ONE of the statements has to be true for the whole conditional to evaluate to true. • if((nValue != null) && (nValue <= 100)) • Returns true • if ( !(nValue > 10) ) • Returns false. It first evaluates the statement nValue>10 which evaluates to true. The ‘!’ operator then returns the logical negation of the operator.

  20. Loops • while • do ...while • for

  21. ‘while’ Loop <html> <head> <title>Conditional Example</title> <script type="text/javascript"> function loops() { var strValue = ""; var nValue = 1; while (nValue <= 10) { strValue += nValue; nValue++; } alert(strValue); } </script> </head> <body onload="loops()"> <p>H1</p> </body> </html>

  22. ‘do-while’ Loop <html> <head> <title>Conditional Example</title> <script type="text/javascript"> function loops() { var strValue = ""; var nValue = 1; do { strValue += nValue; nValue++; } while (nValue <= 10); alert(strValue); } </script> </head> <body onload="loops()"> <p>H1</p> </body> </html> The key difference between the ‘while’ and ‘do-while’ loops is that with the do-while loop, the conditional is evaluated after the first iteration of the body of the loop. This net result, is that we are guaranteed one iteration of the body of the loop. With a ‘while’ loop, the conditional is evaluated first. If the conditional is false the first time around, we never execute the body of the loop.

  23. ‘for’ Loop <html> <head> <title>Conditional Example</title> <script type="text/javascript"> function loops() { var strValue = ""; var nValue = 1; for(var i=0;i < 10; i++) { strValue += nValue; nValue++; } alert(strValue); strValue = ""; for(var i=10;i >= 0; i--) { strValue += nValue; nValue--; } alert(strValue); } </script> </head> <body onload="loops()"> <p>H1</p> </body> </html> First we do the “initializing action” (e.g. var i = 0;) Next we evaluate the conditional. If true, we execute the body. If false, we end the loop. AFTER executing the body, we update (e.g. i++;)

  24. JavaScript Objects JavaScript includes several built-in objects. We have briefly looked at the Math object. Also included are objects that parallel the three key data types we have been working with: String, Number, Boolean. Other important and useful objects are include Date, RegExp (regular expressions), and Array: • Data Types: String, Boolean and Number • Built-in: Math, Date, RegExp • Aggregator: Array

  25. Regular Expressions • Regular Expressions, “RegExp” • Important topic, but can get somewhat involved and complex. • Involves working with strings to look for patterns. • Can be used for security purposes, form validation, data-mining, search-and-replace, etc. • var re5digit=/^\d{5}$/ • ^ indicates the beginning of the string. Using a ^ metacharacter requires that the match start at the beginning. • \d indicates a digit character and the {5} following it means that there must be 5 consecutive digit characters. • $ indicates the end of the string. Using a $ metacharacter requires that the match end at the end of the string.

  26. RegExp <html> <head> <title>RegExp Example</title> <script language="JavaScript1.2" type="text/javascript"> //<![CDATA[ function checkpostal() { var re5digit=/^\d{5}$/ //regular expression defining a 5 digit number //An object can also be created via: var re5digit = new RegExp("^d{5}$"); if (document.myform.myinput.value.search(re5digit)==-1) { //if match failed alert("Please enter a valid 5 digit number inside form"); } else { alert("A valid 5 digit number was entered"); } } //]]> </script> </head> <body> <form name="myform"> <input type="text" name="myinput" size=15> <input type="button" onClick="checkpostal()" value="check"> </form> </body> </html> The 'search' method returns the index of (the first occurrence of) the matched string. If the method does not find the match, it returns -1.

  27. Objects v.s. Primitive Types • With primitive values you just have only the value that was assigned, but JavaScript objects also have built-in functionality. For example, var name = “Bob” -> The variable name is aprimitive data type and includes only the value “Bob”. A String object however, has various things it can “do” such as determine the length of our string. • Often the difference remains invisible with JS creating objects out of primitive types invisibly behind the scenes, and then getting rid of the object when the functionality is no longer needed. However, this results in a performance hit. If you anticipate needing to use the functionality of these objects, it is better to explicitly create the object as demonstrated below. • var myName = “Jones”; // string as a primitive • alert(myName.length); // String object is implicity created (and then discarded) • var myNameObject = new String(”Jones”); // explicit object creation • alert(myName.toUpperCase()); //using the String object’s functionality

  28. Boolean Object • False values: 0, false, empty parentheses • var bool1 = new Boolean(0); • var bool2 = new Boolean(false); • var bool3 = new Boolean(); • True values: 1, true, any non-empty string • var bool4 = new Boolean(1); • var bool5 = new Boolean(true); • var bool6 = new Boolean("false"); // string is not empty, therefore evaluates to true

  29. Pop-Quiz • False values: 0, false, empty parentheses • var bool1 = new Boolean(0); • var bool2 = new Boolean(false); • var bool3 = new Boolean(); • True values: 1, true, any non-empty string • var bool4 = new Boolean(1); • var bool5 = new Boolean(true); • var bool6 = new Boolean("false"); PREDICT: if ( bool4 == true ) Returns true if ( bool4 ) Returns true if ( bool1 ) Returns false if ( bool1==false ) Returns true if ( bool1==“false" ) Returns false (bool1 holds the boolean value of false. We are comparing it with a string)

  30. Boolean Object Nearly all objects can invoke the methods ‘valueOf()’ and ‘toString()’. Exactly what these methods do for a given object is highly dependent on the object in question and the context. In many cases, these methods simply attempt to determine what value(s) is/are stored inside the object and return that information. In the case of a Boolean object, the distinction is subtle: toString() would return either “true” or “false” (i.e. a string), whereas valueOf() would return either true or false (i.e. the Boolean value). <html> <head> <title>Conditional Example</title> <script type="text/javascript"> function bool() { var boolFlag = new Boolean("false"); alert("The primitive value: "+boolFlag.valueOf()); alert("The string value: "+boolFlag.toString()); } </script> </head> <body onload="bool()"> <p>H1</p> </body> </html>

  31. Number Object var n = Number.MAX_VALUE*2; alert(n); //would output ‘infinity’ NOTE: These properties can ONLY be referenced using the ‘Number’ object name. They can not be referenced using an instance of Number: var x = new Number(); alert(x.MAX_VALUE); //undefined

  32. Number class: String Conversions var n = new Number(3.1415); var exp = n.toExponential(); var fixed = n.toFixed(2); alert(exp + "\n" + fixed); alert( fixed + 88 ); //OUTPUTS???? //because toFixed returns a string, using the //’+’ operator gives concatenation

  33. String Conversions <html> <head> <title>Conditional Example</title> <script type="text/javascript"> function numbers() { var newNumber = new Number(34.8896); document.writeln(newNumber.toExponential(3) + "<br />"); document.writeln(newNumber.toPrecision(3) + "<br />"); document.writeln(newNumber.toFixed(6) + "<br />"); var newValue = newNumber.valueOf(); document.writeln(newValue.toString(2) + "<br />"); document.writeln(newValue.toString(8) + "<br />"); document.writeln(newValue.toString(10) + "<br />"); document.writeln(newValue.toString(16) + "<br />"); } </script> </head> <body onload="numbers()"> </body> </html>

  34. String Object Methods

  35. String Instance methods <html> <head> <title>Conditional Example</title> <script type="text/javascript"> //<![CDATA[ function stringHTML(newString) { document.writeln(newString.big() + "<br />"); document.writeln(newString.blink() + "<br />"); document.writeln(newString.sup() + "<br />"); document.writeln(newString.strike() + "<br />"); document.writeln(newString.bold() + "<br />"); document.writeln(newString.italics() + "<br />"); document.writeln(newString.small() + "<br />"); document.writeln(newString.link("http://www.depaul.edu") + "<br />"); } //]]> </script> </head> <body onload="stringHTML('This is a test string')"> </body> </html> Note: I am including these examples on this page for purposes of demonstrating various String instance methods. However, it should be noted that tags such as blink, bold, etc, have been deprecated in favor of using CSS.

  36. String Instance methods <html> <head> <title>Conditional Example</title> <script type="text/javascript"> function stringHTML(newString) { var limit = 3; var arrayTokens = newString.split(" "); var arrayTokensWithLimit = newString.split(" ", limit); document.writeln(newString.charAt(3) + "<br />"); document.writeln(newString.substr(5, 8) + "<br />"); document.writeln(newString.substring(5, 8) + "<br />"); document.writeln(newString.indexOf('t') + "<br />"); document.writeln(newString.toUpperCase() + "<br />"); document.writeln(newString.toLowerCase() + "<br />"); document.write("<br />Contents of arrayTokens <br />"); for(var i=0;i<arrayTokens.length;i++) { document.writeln(arrayTokens[i] + "<br />"); } document.write("<br />Contents of arrayTokensWithLimit <br />"); for(var i=0;i<arrayTokensWithLimit.length;i++) { document.writeln(arrayTokensWithLimit[i] + "<br />"); } } </script> </head> <body onload="stringHTML('This is a test string')"> </body> </html>

  37. Date Object Use the Date object to create an instance of dates. There are several different way of creating a new date object using the ‘new Date()’ constructor: • var dtNow = new Date(); • var dtMilliseconds = new Date(59999000920); • var newDate = new Date("March 12, 1980 12:20:25"); • var newDate = new Date("March 12, 1980"); • var newDate = new Date(1980,03,12,19,30,30,30); • var newDate = new Date(1980,03,12);

  38. Date Object Check out a reference such as http://www.w3schools.com/jsref/jsref_obj_date.asp for more.

  39. Date Instance methods <html> <head> <title>Conditional Example</title> <script type="text/javascript"> function displayDate() { var dtNow = new Date(); document.write(dtNow+"<br>"); document.write('<hr>'); dtNow.setDate(18); //’date’ refers to the day of the month dtNow.setMonth(10); //Note: zero-based dtNow.setYear(2010); dtNow.setHours(13); dtNow.setMinutes(2); document.writeln(dtNow.toString() + "<br />"); document.writeln(dtNow.toLocaleString() + "<br />"); document.writeln(dtNow.toLocaleDateString() + "<br />"); document.writeln(dtNow.toLocaleTimeString() + "<br />"); document.writeln(dtNow.toGMTString() + "<br />"); document.writeln(dtNow.toUTCString() + "<br />"); } </script> </head> <body onload="displayDate()"> </body> </html>

  40. Math Properties and Methods (partial list)

  41. Math Properties and Methods Note that all properties and methods of the Math object must be invoked using the ‘Math’ object itself. In fact, it is not even possible to instantiate (create an object of) the type ‘Math’. Math.sqrt(25); //okay var m = new Math(); //Nope! You can’t create an instance of a Math object m.sqrt(25); //not okay (see above) //All properties and methods of Math must be invoked using ‘Math’

  42. Arrays Creating arrays: • var favColors = ['red', 'blue', 'green', 'yellow']; • var gpaScores = new Array(3.4, 3.9. 2.7); • var emptyArray = new Array(); Working with arrays: • alert(favColors.length); //outputs 4 • var mostFavColor = favColors[0]; //mostFavColor is assigned ‘red’ for (var i=0; i<favColors.length; i++) document.write( favColors[i] + '<br>'); Arrays and other forms of collections are extremely important in programming. However, we will table further discussion for now.

  43. Functions • Give you functions meaningful names (identifiers) • Keep your functions on task: A function should have one key task to perform. Do not try to squeeze too much behavior into one function.

  44. Passing “By Value” v.s. “By Reference” • Variables based on primitive data types are passed to a function “by value”, so if you change the value in the function, it will not be changed in the calling program. • Objects are passed “by reference”. This means that if you modify the object inside the function, this change will be remain in your object even once the function ends. • The concept of passing by reference as opposed to passing by value can take a little getting used to. We will only touch on it for now.

  45. Pass by Value v.s. Pass by Reference <html> <head> <title>Conditional Example</title> <script type="text/javascript"> function alterArgs(strLiteral, arrayObject) { strLiteral = "Override"; arrayObject[1] = "2"; arrayObject[arrayObject.length] = "three"; } function testParams() { var str = "Original Literal"; var ary = new Array("one", "two"); document.writeln("The string literal is " + str +"<br />"); document.writeln("The Array object is " + ary +"<br />"); alterArgs(str, ary); document.write("<hr>"); document.write("After invoking the \"alterArgs\" function:<br />"); document.writeln("The string literal is " + str +"<br />"); document.writeln("The Array object is " + ary +"<br />"); } </script> </head> <body onload="testParams()"> </body> </html>

  46. Function Returns Functions can also return information. This is extremely common and useful. <html> <head> <title>Conditional Example</title> <script type="text/javascript"> function addNumbers() { var sum = addNum(4, 5); document.writeln("The sum of 4 and 5 is " + sum +"<br />"); } function addNum(num1, num2) { var total = num1 + num2; return total; } </script> </head> <body onload="addNumbers()"> </body> </html>

  47. Function Returns <html> <head> <title>Return Function Example</title> <script type="text/javascript"> function findHigher(arg1, arg2) { if (arg1 > arg2) return arg1; else return arg2; } //end findHigher function testFindHigher() { alert("Higher is: " + findHigher(-4, -2)); } //end testFindHigher </script> </head> <body onload="testFindHigher()"> </body> </html>

  48. End of Session 2 • Next Session: • The Browser, The DOM, Dynamic pages, Debugging

More Related