1 / 77

BIT116: Scripting Lecture 05 Part 2

Learn about the different types of JavaScript operators and how they are used in scripts. Explore mathematical, assignment, comparison, and logical operators, as well as their order of precedence.

gcarrillo
Télécharger la présentation

BIT116: Scripting Lecture 05 Part 2

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. BIT116: ScriptingLecture 05 Part 2 Instructor: Craig Duckett cduckett@cascadia.edu Tuesday, July 21st , 2015 Operators, The eval() Function

  2. ASSIGNMENT ANNOUNCEMENTS REMINDER: Submit via StudentTracker. If you haven't already done so, you will need to set up a StudentTracker account in order to upload your Assignment (ZIPPED up in a single file) Assignment 1due on Lecture 7, NEXTTuesday, July 28th, by midnight. Assignment 1 Revisiondue on Lecture 10, Thursday, August 6th, by midnight. Assignment 2due on Lecture 11, Tuesday, August 11th, by midnight. Assignment 2 Revisiondue on Lecture 13, Tuesday, August 18th, by midnight. Assignment 3due on Lecture 14, Thursday, August 20th, by midnight. Assignment 3 Revisondue on Lecture 16, Thursday, August 27th, by midnight.

  3. A Brief Look at Assignment 1: A Basic Calculator

  4. Assignment 1: Part 1 BIG HINT: Look at the eval1.html, eval2.html, eval3.html, and eval4.html files to see how they might be applied and tweaked to successfully complete Assignment 1 Part 1.

  5. Assignment 1: Part 2 For Assignment 1 Part 2, instead of using INLINE SCRIPT you will use a click event to pass a value using a function named calcu() which is defined in an EXTERNAL JAVASCRIPT file called a1_b.js. <script src="a1_b.js"></script> This file will contain the calcu() function which will accept the passed value and work it using a rather lengthy if/else if/else statement (discussed in Lecture 8). An example of the values to pass are included in the comments beside each element. Assignment 1: Part 3 For Assignment 1 Part 3, instead of using INLINE SCRIPT you will use a click event to pass a value using a function named calcu() which is defined in an EXTERNAL JAVASCRIPT file called a1_c.js. <script src="a1_c.js"></script> This file will contain the calcu() function which will accept the passed value and work it using a rather lengthy switch statement (discussed in Lecture 8). An example of the values to pass are included in the comments beside each element. BIG HINT: Look at the eval5.html and eval5.js files to see how they might be applied and tweaked to successfully complete Assignment 1 Part 2 and Assignment 1 Part 3.

  6. Some Common JavaScript Methods & Properties

  7. innerHTML Property • The innerHTML property sets or returns the inner HTML of an element. • Syntax • HTMLElementObject.innerHTML = someString http://faculty.cascadia.edu/cduckett/bit116/Lecture_06/get_element_by_id.html

  8. getElementById() The getElementById() method returns the element that has the idattribute with the specified value. This method is one of the most common methods in the HTML DOM, and is used almost every time you want to manipulate, or get info from, an element on your document. Returns null if no elements with the specified id exists. If more than one element with the specified id exists—although it shouldn't, since each instance of id should be unique—the getElementById() method returns the first element.

  9. JavaScript Operators http://www.w3schools.com/js/js_operators.asp

  10. JavaScript Operators Operators do much of the work in scripts. So far, you have seen examples of the use of the assignment (=) and addition (+) operators. JavaScript offers many other types of operators to perform various operations. This lecture begins by giving you an introduction to the different types of JavaScript operators. Then, you will learn about each operator and its use in scripts. Finally, you will learn about the order of precedence for operators, which determines which operations are performed before others.

  11. Understanding the Operator Types • An operator is a symbol or word in JavaScript that performs some sort of calculation, comparison, or assignment on one or more values. In some cases, an operator provides a shortcut to shorten the code so that you have less to type. • Common calculations include finding the sum of two numbers, combining two strings, or dividing two numbers. Some common comparisons might be to find out if two values are equal or to see if one value is greater than the other. A shortcut assignment operator might be used to assign a new value to a variable so that the variable name does need to be typed twice. • JavaScript uses several different types of operators: • MathematicalThese operators are most often used to perform mathematical calculations on two values. The mathematical operators will probably be the most familiar to you. They use symbols such as +, –, *, and /. • AssignmentThese operators are used to assign new values to variables. • ComparisonThese operators are used to compare two values, two variables, or perhaps two longer statements. They use symbols such as > (for “is greater than”) and < (for “is less than”).

  12. Understanding the Operator Types • LogicalThese operators are used to compare two conditional statements (or to operate on one statement) to determine if the result is true and to proceed accordingly. They use symbols such as && (returns true if the statements on both sides of the operator are true) and || (returns true if a statement on either side of the operator is true). • BitwiseThese are logical operators that work at the bit level (ones and zeros). They use symbols like << (for left-shifting bits) and >> (for right-shifting bits). • SpecialThese are operators that perform other special functions of their own. • In this lecture, you will learn about each of these types of operators. • This will be a general overview of the function of each type of operator, so that you will better know the purpose of all the operator types when you put them to use later. • To begin, you’ll look at the mathematical operators in JavaScript.

  13. Arithmetic Operators

  14. Arithmetic Operators • For a mathematical calculation, you use a mathematical operator. The values that you use can be any sort of values you like. For instance, you could use two variables, two numbers, or a variable and a number. A few of these operators are able to perform a task on a single variable’s value. • As a quick example, you will remember as with Java that you can use the addition operator (+) to add two strings together. Here is an example of two string values being combined with the addition operator: • window.alert("Hello and " + "goodbye."); • You can also use the addition operator when one of the values is a variable, as in this example: • var part2 = "goodbye." • window.alert("Hello and "+ part2); • The addition operator also works when both values are variables, as in the next example: • var part1 = "Hello and "; • varpart2 = "goodbye." • window.alert(part1 + part2);

  15. Arithmetic Operators These examples illustrate how you can use many of the mathematical operators with a number of values and/or variables. This allows you some flexibility in the way you code your scripts. The three operators that work on single values are the increment, decrement, and unary negation operators. The increment and decrement operators are actually shortcuts to adding or subtracting 1, so learning how to use them could save you some coding time. The mathematical operators and their functions are summarized on the next slide. The following slides discuss each operator in more detail.

  16. The Addition Operator: + • As you have seen, the addition operator can be used to combine two strings. It is also used to add numbers in mathematical calculations. • Variables for Addition Results • One use of the addition operator is to add two numbers to get the mathematical result. When adding numerical values, you often assign the result to a variable and use the variable later to make use of the result. For example, to calculate the value of 4 plus 7 and show the result, you could code it like this: • vartheSum = 4 + 7; • window.alert(theSum); • The result is an alert that says 11. • To make the example a little more complex, you could change one of the numbers to a variable: • var num1 = 4; • vartheSum = num1 + 7; • window.alert(theSum);

  17. The Addition Operator: + CONTINUED • Taking the example one step further, you could make both of the numbers variables: • var num1 = 4; • varnum2 = 7; • vartheSum = num1 + num2; • window.alert(theSum); http://faculty.cascadia.edu/cduckett/bit116/Lecture_07/addition.html

  18. The Addition Operator: + CONTINUED • Type Conversions in Addition Calculations • It is important to note how JavaScript performs type conversion when working with the mathematical operators. When you use the addition and other mathematical operators, you need to be aware that JavaScript automatically converts different values, like an integer (a nondecimalnumeric value) and a float (a decimal numeric value) to the appropriate type. For instance, you might have the following code: • var num1 = 4.73; // This is a float • varnum2 = 7; // This is an int • vartheSum = num1 + num2; • window.alert(theSum); • JavaScript added the integer and the float together and gave back a float: 11.73. • JavaScript does this often, so you need to make sure that you have the right sort of values when you begin adding.

  19. The Addition Operator: + CONTINUED • Type Conversions in Addition Calculations CONTINUED • If you add a number and a string, the result will come out as though you had added two strings. Look at this example: • var num1 = 4; // This is an int • varnum2 = "7"; // This is a string • vartheSum = num1 + num2; • window.alert(theSum); • This looks as if it would be adding the numbers 4 and 7, since they both appear to be numbers. The trouble is that the 7 is a string in this case, not a number, because it has quotes around it. This causes the 4 to be converted to a string, and then the two strings are combined, not added. • The result would be: "4" + "7" = 47. http://faculty.cascadia.edu/cduckett/bit116/Lecture_07/stringsnumbers.html

  20. The Addition Operator: + CONTINUED • Special Rules for Addition in JavaScript • If one of the operands is NaN*, the result will be NaN • If one of the operands is a string, the other operand is converted into a string and the strings are concatenated. • If both operands are strings, the strings are concatenated. • *NaN = Not a Number

  21. The Subtraction Operator: - • The subtraction operator is used to subtract the value on its right side from the value on its left side, as in mathematics. Here is an example: • vartheResult = 10 - 3; • window.alert(theResult); • This code simply subtracts 3 (the number on the right of the operator) from 10 (the number on the left of the operator). The result is an alert that says 7. • As with the addition operator, you can use variables to hold the numbers you are working with, as in this example: • var num1 = 10; • varnum2 = 3; • vartheResult = num1 - num2; • window.alert(theResult); • The result is the same as the previous example: an alert that says 7.

  22. The Subtraction Operator: - CONTINUED • Special Rules for Subtraction in JavaScript • If one of the operands is NaN, the result will be NaN • If one of the operands is a data type other than a number, JavaScript will try to convert that data type and perform the division; if it can't, the result will be NaN. http://faculty.cascadia.edu/cduckett/bit116/Lecture_07/subtraction.html

  23. The Multiplication Operator: * • The multiplication operator is used to multiply the value on its right side by the value on its left side. Again, this is just like mathematical multiplication. • The next example shows this operator in action: • var num1 = 4; • varnum2 = 5; • vartheTotal = num1 * num2; • window.alert(theTotal); • Here, you get an alert that says 20, the result of 4 times 5. http://faculty.cascadia.edu/cduckett/bit116/Lecture_07/multiplication.html

  24. The Multiplication Operator: * CONTINUED • Special Rules for Multiplication in JavaScript • If one of the operands is NaN, the result will be NaN • If one of the operands is a data type other than a number, JavaScript will try to convert that data type and perform the division; if it can't, the result will be NaN.

  25. The Division Operator: / • The division operator is used to divide the value on its left side by the value on its right side. For example, the code 4/2 means 4 divided by 2 and gives the result of 2. • For a JavaScript example of this in action, take a look at this code: • var num1 = 10; • varnum2 = 2; • vartheResult = num1/num2; • window.alert(theResult); • This gives you an alert that says 5, the result of dividing 10 by 2.

  26. The Division Operator: / CONTINUED • Division by Zero • When you use the division operator, you need to be careful that you do not end up dividing by zero in some way. If you do, the result is going to be either infinity or undefined, depending on your browser. The code that follows shows an example of this happening (although it is unlikely to occur exactly in this way): • varnum1=10; • var num2=0; • vartheresult=num1/num2; • window.alert(theresult); • If you placed this code in a document, you might see an alert box like this: • Infinity

  27. The Division Operator: / CONTINUED • Type Conversions in Division Calculations • Another thing to remember with division is that if you have two values that do not divide evenly, the result is converted into a float, and thus will have decimal places. The code that follows shows an example: • var num1 = 3; • varnum2 = 4; • vartheResult = num1/num2; • window.alert(theResult); • The result in this case is 0.75, which is what you see in the alert box. Some browsers may not show the 0 before the decimal, and display just .75 in the alert box instead. http://faculty.cascadia.edu/cduckett/bit116/Lecture_07/division.html

  28. The Division Operator: / CONTINUED • Special Rules for Division in JavaScript • If one of the operands is NaN, the result will be NaN • If zero is divided by zero, the result will be NaN • If any number is divided by zero, the result will be Infinity • If one of the operands is a data type other than a number, JavaScript will try to convert that data type and perform the division; if it can't, the result will be NaN.

  29. The Modulus Operator: % • The modulus operator is used to divide the number on its left side by the number on its right side, and then give a result that is the integer remainder of the division. Think back to when you learned long division and used remainders as part of the answer rather than converting to decimals or fractions. Dividing 11 by 2 gives 5 with a remainder of 1. The remainder of 1 is what the modulus operator gives you when you write 11%2. • The following is an example in JavaScript: • var num1 = 11; • varnum2 = 2; • vartheResult = num1 % num2; • window.alert(theResult); • The result is an alert box that shows the value of the remainder, which is 1. If the calculation had no remainder, the result would be 0. • This is the last of the mathematical operators that work on two values at the same time. The next operators work on only one value at a time. http://faculty.cascadia.edu/cduckett/bit116/Lecture_07/modulus.html

  30. The Increment Operator: ++ • The increment operator can be used on either side of the value on which it operates. It increases the value it is operating on by 1, just like adding 1 to the value. The actual result depends on whether the operator is used before or after the value it works on, called the operand. This operator is often used with variables, and often within loops . • The Increment Operator Before the Operand • When the increment operator is placed before the operand, it increases the value of the operand by 1, and then the rest of the statement is executed. Here is an example: • var num1 = 2; • vartheResult = ++num1; • In this case, the variable num1 begins with a value of 2. However, when the code assigns the value to the variable theResult, it increments the value of num1 before the assignment takes place. The increment occurs first because the increment operator is in front of the operand. • So, the value of num1 is set to 3 (2+1) and is then assigned to the variable theResult, which gets a value of 3. http://faculty.cascadia.edu/cduckett/bit116/Lecture_07/increment_before.html

  31. The Increment Operator: ++ CONTINUED • The Increment Operator After the Operand • If you place the increment operator after the operand, it changes the value of the operand after the assignment. • Consider this example: • var num1 = 2; • vartheResult = num1++; • As in the previous example, num1 begins with the value of 2. On the next line, the increment operator is used after the operand. This means that the code assigns the current value of num1 to the variable theResult, and after that is done, it increments the value of num1. So, only after this assignment is complete do you have a new value for num1. The variable theResultis given a value of 2, and then num1 is changed to 3. If you use num1after this, it will have a value of 3. http://faculty.cascadia.edu/cduckett/bit116/Lecture_07/increment_after.html

  32. The Increment Operator: ++ CONTINUED • Another way to see how the increment operator works before and after the operand is to run the following script in your browser. Notice what the values are in the first alert and what they are in the second alert. • num1 = 2; • result = ++num1; • alert("num1 = " + num1 + " result = " + result); • num1 = 2; • result = num1++; • alert("num1 = " + num1 + " result = " + result); • In the first alert box, you will see num1 = 3 result = 3. Since the ++ operator is used before the operand here, the value of num1 is increased by 1 and then assigned to the result variable. In the second alert box, you will see num1 = 3 result = 2. This is because the ++ operator is used after the operand, so the value of num1 is increased after it has been assigned to the result variable. The result variable gets a value of 2, but num1 will be increased to 3. • Note: Don’t worry if the difference between using the increment operator before and after the operand is still not clear to you. When you learn how to use loops later in the quarter, you will see how the placement of this operator can be quite important.

  33. The Decrement Operator: -- • The decrement operator works in the same way as the increment operator, but it subtracts 1 from the operand rather than adding 1 to it. As with the increment operator, its placement before or after the operand is important. • If you place the decrement operator before the operand, the operand is decremented, and then the remainder of the statement is executed. Here is an example: • var num1 = 2; • vartheResult = --num1; • Here, the variable num1 is given a value of 2. In the next line, the code subtracts 1 from num1 and then assigns the result to the variable theResult. Thus, the variable theResultends up with a value of 1 (2–1). http://faculty.cascadia.edu/cduckett/bit116/Lecture_07/decrement_before.html

  34. The Decrement Operator: -- CONTINUED • When you place the operator after the operand, as in the next example, the rest of the statement is executed and the operand is decremented afterward: • var num1 = 2; • vartheResult = num1--; • This time, the variable theResultis assigned a value of 2, and then num1 is decremented to 1. • If you use num1 after this line, it will have a value of 1. • As with the increment operator, the decrement operator becomes important when you work with loops, as you will learn in a later lecture. http://faculty.cascadia.edu/cduckett/bit116/Lecture_07/decrement_after.html

  35. The Unary Negation Operator: - • Unary negation is the use of the subtraction sign on only a single operand. This operator creates a negative number or negates the current sign of the number (positive or negative). Here is an example of assigning a negative value to a number: • varnegnum = -3; • This defines a variable with a value of negative 3. Basically, the operator tells the browser that the 3 is “not positive,” because it negates the default sign of positive by placing the negation operator ahead of the number. • You can also use the unary negation operator to help show the addition or subtraction of a negative number, as in this example: • vartheResult = 4 +( -3); • Notice the parentheses around the –3 portion of the statement. As in math, you can use parentheses to set the order of operations (as you’ll learn later in this chapter) or just to clarify the order visually. Here, the parentheses aren’t necessary, but they help organize that code so that you can see that it is adding –3 to 4. You could have written this code as well: • vartheResult = 4 + -3; // This doesn’t look as nice, but it still works.

  36. The Unary Negation Operator: - CONTINUED • You may be thinking that an even easier way to write the same thing looks like this: • vartheResult = 4 - 3; • You’re right, this is the simplest way to write it; but it uses subtraction rather than unary negation. • To make it appear more clearly, you could use this operator on a variable value, which simply negates the sign on the number represented by the variable: • var x = 4; • vary = 3; • varz = -y; • This assigns the variable z the unary negated value of y, which is –3. • Now that you’ve learned about the mathematical operators, it’s time to turn to the assignment operators.

  37. Assignment Operators

  38. Assignment Operators • Understanding Assignment Operators • Assignment operators assign a value to a variable. They do not compare two items, nor do they perform logical tests. • When you learned about variables in Chapter 3, you saw how the basic assignment operator, the single equal sign (=), is used to give an initial value or a new value to a variable, as in this example: • varmyTime = 0; • As you know, this assigns a value of 0 to a variable myTime. • The other assignment operators also give new values to variables, but they do so in slightly different ways because they perform a simple calculation as well. These operators are particularly useful within loops, as you’ll learn in later lectures.

  39. The Assignment Operator: = • You have been using the assignment operator since the good ol' days of Java. • It assigns the value on the rightside of the operator to the variable on the left side, as in this example: • var population = 1500000; • This assigns the value of 1500000to the variable population. RIGHT to LEFT

  40. The Add-and-Assign Operator: += • The += operator adds the value on the right side of the operator to the variable on the left side and then assigns to the variable that new value. In essence, it is a shortcut to writing the type of code shown here: • varmyMoney = 1000; • myMoney = myMoney + 1; • Here, the variable myMoneyis created and assigned a value of 1000. The code then changes the value by assigning it a value of itself plus 1. The value assigned to the myMoneyvariable is 1001. • Instead of writing the variable name an extra time, you can use the add-and-assign operator to shorten the code. The following code gives the same result as the previous example, but saves a little typing: • varmyMoney = 1000; • myMoney += 1; // Same as: myMoney = myMoney + 1; • // Result is: 1001 = 1000 + 1 • Using the add-and-assign operator, this code adds 1 (the value on the right) to myMoney(the variable on the left), assigning the new value of 1001 to the variable myMoney.

  41. The Add-and-Assign Operator: += CONTINUED • This operator can be used to add any value, not just 1. For example, you could add 5 in the assignment, as in this example: • varmyMoney = 1000; • myMoney += 5; // Same as: myMoney = myMoney + 5; • This time, myMoneyends up with a value of 1005. • You can even use a variable rather than a plain number value on the right side, as in this example: • varmyMoney = 1000; • varbonus = 300; • myMoney += bonus; // Same as: myMoney = myMoney + bonus • // Result is: 1300 = 1000 + 300 • Here, bonus has a value of 300, which is added to the variable myMoney, and then myMoney is assigned the result of 1300. In this way, the value of the bonus variable can be changed to affect the result of the assignment. http://faculty.cascadia.edu/cduckett/bit116/Lecture_07/plusequals.html

  42. The Add-and-Assign Operator: += CONTINUED • This assignment operator, like the addition mathematical operator, also works with strings. • Thus, you could add on to the end of a string value using this operator: • varmyName = "Bob"; • myName += "by"; // Same as: myName= myName+ "by"; • // Result: "Bobby" = "Bob" + "by" • This adds the string “by” to the end of the string “Bob”, which yields the string “Bobby”.

  43. The Subtract-and-Assign Operator: -= • The –= operator works like the += operator, except that it subtracts the value on the rightside of the operator from the variable on the left side. This value is then assigned to the variable. • Here is an example of this operator in action: • varmyMoney = 1000; • varbills = 800; • myMoney -= bills; // Same as: myMoney = myMoney– bonus; • // Result is: 200 = 1000 - 800 • This example subtracts the value of the bills variable (800) from the myMoneyvariable and assigns the result to myMoney. In the end, myMoneyhas a value of 200. • Since this is so similar to the add-and-assign operator, let’s move on to the next one (which is also very similar). http://faculty.cascadia.edu/cduckett/bit116/Lecture_07/minusequals.html

  44. The Multiply-and-Assign Operator: *= • The *= operator multiples the value on the right side of the operator by the variable on the left side. The result is then assigned to the variable. • The next example shows this operator at work: • varmyMoney = 1000; • varmultBy = 2; • myMoney *= multBy; // Same as: myMoney = myMoney* multBy; • // Result is: 2000 = 1000 * 2 • Here, the variable myMoneyis multiplied by the value of the multByvariable, which is 2. The result of 2000 is then assigned to the variable myMoney.

  45. The Divide-and-Assign Operator: /= • The /= operator divides the variable on the left side of the operator by the value on the right side. The result is then assigned to the variable. • Here is an example: • varmyMoney = 1000; • varcutPayBy = 2; • Mymoney /= cutPayBy; // Same as: myMoney = myMoney/ cutpayBy; • // Result is: 500 = 1000 / 2 • In this example, the variable myMoneyis divided by the value of the variable cutPayBy, which is 2. • The result of 500 is then assigned to the myMoneyvariable.

  46. The Modulus-and-Assign Operator: %= • Like the other assignment variables that also perform math, the %= operator does a calculation for the variable assignment. It divides the variable on the left side of the operator by the value on the right side, takes the integer remainder of the division, and assigns the result to the variable. Here is how you might assign a value to the mymoney variable using the modulus-and- assign operator: • varmyMoney = 1000; • varcutPayBy = 2; • myMoney %= cutPayBy; // Same as: myMoney = myMoney% cutPayBy; • // Result is: 0 = 1000 % 2 • Here, the variable myMoneyis divided by the value of the variable cutPayBy, which is 2. The result of that is 500 with no remainder, meaning that the end result of the calculation is 0. • Thus, 0 is the value that gets assigned to the variable myMoney. (Yikes!)

  47. Comparison Operators

  48. Understanding Comparison Operators Comparison operators are often used with conditionalstatements and loops in order to perform actions only when a certain condition is met. Since these operators compare two values, they return a Boolean value of either true or false, depending on the values on either side of the operator.

More Related