Manipulation of Variables and Data

Now that you have learned a little about variables and data, you need to know how to work with them. The two basic tools for manipulating data are operators and methods.

Operators

JScript allows the creation of mathematical expressions. An expression is essentially a mathematical sentence—for example, 5+6 or myVar+4. An operator is like a verb in the sentence; it performs an action. In the expression 5+6, the plus sign is the operator because it performs the action of adding the two numbers. Table 8-2 describes common mathematical operators.

Table 8-2 Common Mathematical Operators

Operator Action Performed
= Assignment. Assigns a value or an expression to a variable. For example, myVar=6 assigns the value 6 to the myVar variable.
+ Addition or concatenation. Adds two values or combines (concatenates) two strings. For example, 1+2 equals 3, and "sample"+"text" equals "sampletext".
- Subtraction. Subtracts one number from another.
- Unary negation. Makes the associated value a negative value. For example, -3 is read as "negative three."
/ Division. Divides one number by another.
* Multiplication. Multiplies one number by another.
% Modulo. Returns the remainder when one number is divided by another. For example, 7%4 equals 3.
+=, -=, *=, /=, %= Arithmetic operation with assignment. Performs an action with the contents of a variable and assigns the result to the variable. For example, if the variable myVar has a value of 5, the expression myVar+=6 adds 6 to the value; as a result, the value of myVar now equals 11. Thus, the expression myVar+=6 is equivalent to myVar=myVar+6. When it is used with strings, the operator += concatenates one string with another. For example, if the value of myVar equals "sample", the expression myVar+="text" changes the value of myVar to "sampletext".
++ Increment. Adds 1 to a value. For example, if the value of myVar is 6, the expression myVar++ changes that value to 7. Thus, the expression myVar++ is equivalent to myVar=myVar+1.
-- Decrement. Subtracts 1 from a value. For example, if the value of myVar is 6, the expression myVar-- changes that value to 5. Thus, the expression myVar-- is equivalent to myVar=myVar-1.
( ) Group. Used to group parts of an expression. For example, the expression 4+(6/2) divides 6 by 2 and then adds the result to 4, resulting in a value of 7. In contrast, the expression (4+6)/2 adds 4 and 6 and then divides the result by 2, resulting in a value of 5.

Code Listing 8-5 demonstrates the use of the + operator. When the browser processes this code, you see the display shown in Figure 8-5.

Code Listing 8-5.

 <HTML> <HEAD> <TITLE>Listing 8-5</TITLE> <SCRIPT LANGUAGE="JavaScript"> var a=15 var b=`abc' var c=`10' var d=true document.write("Variable a=15, b=`abc', c=`10' and d=true<BR>") document.write("a+10 equals "+(a+10)+"<BR>") document.write("b+'def' equals "+(b+'def')+"<BR>") document.write("c+a equals "+(c+a)+"<BR>") document.write("b+d equals "+(b+d)+"<BR>") document.write("a+d equals "+(a+d)+"<BR>") </SCRIPT> </HEAD> </HTML> 

click to view at full size.

Figure 8-5. Using the + (addition or concatenation) operator.

The first mathematical expression is a+10. Because the variable a has been assigned the value 15, the expression a+10 adds the number 10 to the number 15, resulting in a value of 25. In the next line, we add the letters def to the end of variable b (a string containing the letters abc), resulting in the string abcdef. (In other words, the two strings are concatenated.)

The next three lines illustrate what happens when you try to add variables that are of different data types. When a string is added to a nonstring, the nonstring is usually converted to a string and the two are then concatenated. For instance, the expression c+a, in which c is a string containing the two characters 1 and 0 (10) and a is the number 15, results in the string 1015. In the next line, the Boolean variable d (which has been assigned the value true) is added to string b (which has the string value abc), resulting in the string abctrue. (The Boolean value is converted to a string and then concatenated to the value of variable b.) Finally you can see the results of adding a Boolean variable to a number type. The expression a+d is the equivalent of 15+true. In such an operation, a Boolean value of true is treated as 1, while false is treated as 0. Thus, the expression 15+true evaluates to 16.

Type Conversion

Although it is often useful to have JScript automatically convert one type of data to another, you might not always want such a conversion to occur. Several built-in methods let you control data type conversion, ensuring that data ends up in the desired type.

You can determine the current type of a variable by using the typeof operator. This operator returns one of six possible values: string, number, Boolean, object, function, and undefined. Code Listing 8-6 demonstrates the typeof operator in use. Figure 8-6 shows how the browser displays the results of this code.

Code Listing 8-6.

 <HTML> <HEAD> <TITLE>Listing 8-6</TITLE> <SCRIPT LANGUAGE="JavaScript"> var a=15 var b=`abc' var c=`10' var d=true var e=window var f document.write("Variable a=15, b=`abc', c=`10', d=true, ") document.write("e=window, and f is not equal to anything.<BR>") document.write("a is of type "+typeof(a)+"<BR>") document.write("b is of type "+typeof(b)+"<BR>") document.write("c is of type "+typeof(c)+"<BR>") document.write("d is of type "+typeof(d)+"<BR>") document.write("e is of type "+typeof(e)+"<BR>") document.write("f is of type "+typeof(f)+"<BR>") </SCRIPT> </HEAD> </HTML> 

click to view at full size.

Figure 8-6. Using the typeof operator.

Another way to test a variable or an expression is by using the isNaN method. This test returns true if the item evaluated is not a number (and cannot be expressed as a number) and returns false if it is a number. To test a variable or an expression, enclose it in parentheses after the isNaN method is called (making it an argument passed to the isNaN method). Thus, isNaN("test") returns true because "test" is a string and is not a number. The expression isNaN(13) returns false because 13 is a number, whereas isNaN("13") returns false because even though 13 (in quotation marks) is a string, it can be expressed easily as a number. If a variable a has the value 13, the expression isNaN(a) is the equivalent of isNaN(13) and evaluates to false because 13 is a number.

You can change a string to a number using the parseInt method or the parseFloat method. The parseInt method discards any characters after the first nonnumber character (even a decimal point) in a string. The parseFloat method works the same way except that it retains an existing decimal point. A number (or other data type) can be converted to a string with the toString method, which is a built-in method of all standard data types.

Code Listing 8-7 demonstrates the use of these methods to manipulate variables before adding them together. The results are shown in Figure 8-7.

Code Listing 8-7.

 <HTML> <HEAD> <TITLE>Listing 8-7</TITLE> <SCRIPT LANGUAGE="JavaScript"> var a=15 var b=`10.5' var c=`12a5' document.write("Variable a=15, b=`10.5', and c=`12a5'<BR>") document.write("isNaN(a) evaluates to "+isNaN(a)+"<BR>") document.write("isNaN(b) evaluates to "+isNaN(b)+"<BR>") document.write("isNaN(c) evaluates to "+isNaN(c)+"<BR>") document.write("a+b equals "+(a+b)+"<BR>") document.write("a+parseInt(b) equals "+(a+parseInt(b))+"<BR>") document.write("a+parseFloat(b) equals "+(a+parseFloat(b))+"<BR>") document.write("a+parseInt(c) equals "+(a+parseInt(c))+"<BR>") document.write("a+parseFloat(c) equals "+(a+parseFloat(c))+"<BR>") document.write("a+a equals "+(a+a)+"<BR>") document.write("a+a.toString() equals "+(a+a.toString())+"<BR>") </SCRIPT> </HEAD> </HTML> 

click to view at full size.

Figure 8-7. Effects of converting one data type to another.

Notice that when we use parseInt on variable b in Code Listing 8-7, the resulting value is a whole number, whereas using parseFloat results in a number with a decimal point. Also notice that in the last expression in this sample, we add the variable a (which is a number) to a expressed as a string, which results in a concatenated string.

NOTE
You can convert a string to an array and vice versa with the split and join methods. These methods take a single string as an argument. The code myArray=myString.split(",") will convert myString to an array and assign the results to myArray. The contents of myString before the first comma (the argument passed to the split method) will be assigned to myArray[0], the contents between the first and second commas to myArray[1], and so on. The join method performs the opposite action and combines the elements of an array into a single string, separated by the character or characters passed as an argument. To learn more about these methods, consult the Microsoft Developer Network Scripting Web site. To get there, visit the MSDN Online Resource page at http://msdn.microsoft.com/resources/schurmandhtml.htm, or open the file named MSDN_OL.htm on the companion CD, and choose JScript Language Reference.

Methods and Properties of Data Types

Each data type supports its own special methods and properties. As you will remember, methods are actions that can be performed on the data; properties give us information about the data. Virtually all data objects support the toString method, discussed earlier, and the valueOf method, which returns the value of the object. A useful property is length, which acts differently depending on the type of data.

The following sections take a brief look at some of the methods and properties supported by various data types. You can find details about all these methods and properties on the Microsoft Developer Network Scripting Web site; see msdn.microsoft.com/scripting.

Strings

Variables of the string type can use the methods shown in Table 8-3.

Table 8-3 Methods for Variables of Type String

anchor FromCharCode Split
big IndexOf strike
blink Italics sub
bold LastIndexOf substr
charAt Link substring
charCodeAt Match sup
concat Replace toLowerCase
fixed Search toUpperCase
fontcolor Slice toString
fontsize Small valueOf

These methods are used in the same way as methods in the Dynamic Object Model are, and they are executed in code using standard dot notation. For example, given a variable named myString, the code myString.toLowerCase() applies the toLowerCase method to myString, setting all text contained in the variable myString to lowercase.

Code Listing 8-8 provides examples of some of the most useful of these methods. To see what they produce, refer to Figure 8-8.

Code Listing 8-8.

 <HTML> <HEAD> <TITLE>Listing 8-8</TITLE> <SCRIPT LANGUAGE="JavaScript"> var a="Fourscore and seven years ago..." doc=document doc.write("a is a string equal to <B>"+a+"</B>") doc.write("<BR>") doc.write("a.charAt(3) is <B>"+a.charAt(3)+"</B>") doc.write("<BR>") doc.write("a.indexOf(`and') is <B>"+a.indexOf(`and')+"</B>") doc.write("<BR>") doc.write("a.lastIndexOf(`s') is <B>"+a.lastIndexOf(`s')+"</B>") doc.write("<BR>") doc.write("a.replace(`Four','Two') is <B>"+a.replace(`Four','Two')+"</B>") doc.write("<BR>") doc.write("a.substring(3,12) is <B>"+a.substring(3,12)+"</B>") doc.write("<BR>") doc.write("a.length is <B>"+a.length+"</B>") </SCRIPT> </HEAD> </HTML> 

In Code Listing 8-8, the charAt method returns the character that is found at a particular location (index) in the string. Because strings are zero-ordered, the code charAt(3) returns the fourth character in the string. The indexOf method searches through the string and returns the first position of a specified character or characters within that string. The lastIndexOf method searches the string backward for a character or characters. To replace one set of characters in a string with another, we used the replace method (replacing Four with Two). The substring method returns a part of the string, given a start and an end point. The length property returns the number of characters in the string.

click to view at full size.

Figure 8-8. Using string methods.

Numbers and Booleans

Numbers and Boolean variables support only the toString and valueOf methods. They do not support a length property.

The Math Object

In addition to the toString and valueOf methods, a useful way to manipulate numbers in JScript is with the Math object. This object supports many methods that perform mathematical operations on numbers; for example, you can use the pow method to raise a number to a power or the cos method to take the cosine of a number. Here is a list of the methods supported by the Math object:

abs acos asin atan atan2 ceil
cos exp floor log max min
pow random round sin sqrt tan

Some of these methods are shown in Code Listing 8-9. The display in Figure 8-9 illustrates how they work.

Code Listing 8-9.

 <HTML> <HEAD> <TITLE>Listing 8-9</TITLE> <SCRIPT LANGUAGE="JavaScript"> var a=2.767 document.write("a is a number equal to "+a+"<BR>") document.write("Math.cos(a) equals "+Math.cos(a)+"<BR>") document.write("Math.pow(a,2) equals "+Math.pow(a,2)+"<BR>") document.write("Math.floor(a) equals "+Math.floor(a)+"<BR>") document.write("Math.round(a) equals "+Math.round(a)+"<BR>") document.write("Math.random() equals "+Math.random()+"<BR>") document.write("Math.random() equals "+Math.random()+"<BR>") document.write("Math.random() equals "+Math.random()+"<BR>") </SCRIPT> </HEAD> </HTML> 

click to view at full size.

Figure 8-9. Using the Math object.

The first use of the Math object in Code Listing 8-9 finds the cosine of the value of variable a, using the cos method. Next we use the pow method to raise a to the second power, which returns the value of a squared. The floor method removes any digits after the decimal point, while the round method rounds a to the nearest whole number. The random method returns a randomly generated number between (and including) 0 and 1 each time the method is called; notice that each instance of random results in a different number.

Arrays

Arrays support the concat, join, reverse, slice, and sort methods. You can use the concat method to combine two arrays into one. The join method creates a string from all the elements in the array, separated with a dividing character that you specify. The reverse method reverses the order of the elements of the array. The slice method returns part of an array. The sort method lets you reorder the elements of an array. The length property returns the number of elements in the array. For example, if an array has indexes numbered 0 through 9, its length will be 10. This is true even if some of the indexes in the range are undefined.

This chapter has laid the foundation for working with data in JScript. In the next chapter, we will look at how to control the flow of your JScript programs through the use of functions, which package blocks of script into easily addressable units, and conditional statements, which let your script react differently in different situations. We will also look at loops, which offer a simple way to repeat actions.



Dynamic HTML in Action
Dynamic HTML in Action
ISBN: 0735605637
EAN: 2147483647
Year: 1999
Pages: 128

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net