Chapter 3. Dealing with Data and Variables

CONTENTS

CONTENTS>>

  •  Literals
  •  Variables
  •  Primitive and Compound Data
  •  Arrays
  •  Summary

While the heart of a scripting or programming language is contained in its statements and structure, its utility is in the way the language handles data. As noted in Chapter 2, "An Orientation to JavaScript," JavaScript is a weakly typed or untyped language, so the burden of keeping track of data types is left largely to the inner workings of the language.

However, JavaScript is more sophisticated than you might expect of a weakly typed language. In addition to strings, numbers, and Boolean values, JavaScript data can include objects, including arrays and functions. Each of these data types is important to understand before proceeding so that when you're working on your design, you can decide which data types are required to create a certain effect. If you're new to programming, you might need to study the data types carefully; while a newcomer to programming need not fully understand all the nuances of the data types immediately, trying out different types of data and experimenting with their characteristics is important. Later, as you gain experience, you will be able to solve many design problems with a clear understanding of the types of data that JavaScript generates and you'll be solving programming problems that help execute your design.

Literals

The raw data that make up the root of data types are called "literals." These are, in effect, literally what they represent themselves to be. Numbers, strings, and Boolean values make up the core set of literals in JavaScript. Little mystery exists with literals, but important differences exist between them.

Numbers

The fundamental data in most computer languages are numbers. Because JavaScript is weakly typed, all numbers are treated as floating-point, so you need not distinguish between integers and floating-point literals. All of the following values are treated as numeric literals:

223.48  20  0  500.33

When assigning numeric literals to names (identifiers), you simply write them in their raw form, with no required quotation marks or other characters, to represent decimal values. With numbers other than decimal values or very large numbers, special requirements exist.

Scientific Notations

If you need scientific notations or are returned a value written in a scientific notation, you will be glad to know that they are written in standard format. For example, you might see the value 9.00210066295925e+21 on the screen after your script has calculated some really big numbers.

The letter e is followed by a plus or minus sign and from one to three integers. (The sign is placed in a returned result but is optional if you write your own notation.) The integers following the e are the exponent, and the rest of the number (preceding the e notation) is multiplied by 10 to the power of the exponent. In most JavaScript applications, numbers with scientific notations do not appear, but if they do, they are treated for purposes of calculations just like any other number.

Hexadecimal Literals

Base 16 or hexadecimal literals have a special preface to alert the parser that the combination of numbers and letters is indeed made up of special values. All hexadecimal literals are prefaced by 0x (zero-x), followed by 0 9, A F characters indicating a hexadecimal value. For example, the color red in hexadecimal is FF0000; in JavaScript, it is written as 0xFF0000.

All calculations done in hexadecimal values in JavaScript are returned as decimal values. For example, if you add 0xa8 to 0xE3, the resulting value in decimal is 395 instead of the hexadecimal value 18b. Fortunately, JavaScript provides a way to express hexadecimal values using the toString( ) method. (The decimal- tohexadecimal conversion script in Chapter 1, "Jump-Starting JavaScript," used the same method.) By including the number base as an argument, you can return a hexadecimal value. The following script shows how.

hexNota.html
<html>  <head>  <title> Hexadecimal Values </title>  <script language="JavaScript">  var alpha=0xdead;  var beta=0xbeef;  var gamma=(alpha + beta).toString(16);  document.write(gamma);  </script>  </head>  <body bgcolor="springgreen">  </body>  </html>

Hexadecimal values' most familiar application in JavaScript and HTML is as sixcharacter color values. It requires no calculations for a color other than conversion from decimal. However, many other occasions might arise in which calculations using hexadecimal values occur, and knowing how to generate hexadecimal results in JavaScript can be useful.

Strings

Like other programming languages, string literals are text. Any set of characters placed in quotation marks (single or double) make up a string literal. For example, the following are all string literals:

"JavaScript makes things jump."  '1-2 Buckle your shoe'  "54321"  "200 Bloomfield Avenue"  'My dog is named "Fred"'

Numbers in a string are treated as text, not as values that can be calculated. Quotation marks within quotation marks need to be nested. That is, if the initial quotation is a double quote, the two single quote marks must be within the double quotes, or vice versa, as in the last example. For example, the output of the string literal 'My dog is named "Fred"' returns

My dog is named "Fred"
The Escape Sequence for Strings

You may also include escape characters and sequences by prefacing a code with a backslash (\) for additional control over string literals. For example, the literal \' prints an apostrophe without affecting the literal itself. Other escape codes include the following:

  • \n New line

  • \' Single quote or apostrophe

  • \" Double quote

  • \\ Backslash

The following script shows how you can use strings, including escape sequences, to order the output in an alert( ) function.

escape.html
<html>  <head>  <title> Escape </title>  <script language="JavaScript">  var alpha="Welcome to Bill\'s Burgers\n";  var beta="_____________________";  var gamma="\nThe \"Best\" you can buy."  alert(alpha + beta + gamma);  </script>  </head>  <body bgcolor="palegoldenrod">  </body>  </html>

Figure 3.1 shows the outcome that you can expect when you launch the program.

Figure 3.1. JavaScript uses escape sequences to format data.

graphics/03fig01.gif

While the formatting using the escape sequences works well with the alert( ) function, it does not work the same with document.write( ). The character substitutions for apostrophes and quotes return the same results, but the \n (new line) sequence does not. Because document.write( ) places text into the HTML page itself rather than a special box, as do the alert( ) and prompt( ) functions, you can use HTML tags such as <br> to achieve a new line with document.write( ). However, if you attempt to use HTML formatting tags with the alert( ) or prompt( ) functions, you will find that they either will not work as expected or will not work at all.

Boolean Values

A Cork University professor named George Boole developed a mathematical system of logic that became known as Boolean mathematics. Much of the logical structure of computer engineering and programming is based on Boole's system. The Boolean values in JavaScript are two literals, true and false (1 or 0, yes or no). The Boolean literals are derived from logical comparisons, testing a truth value and then using that value (true or false) for another operation. Most common Boolean tests and values are found in conditional statements that have this form:

If a condition is true         Flag=true  Else         Flag=false

Using the flag value, different paths are followed, usually in the form of a statement. Chapter 5, "JavaScript Structures," covers conditional statements in detail; in that chapter, you will see extensive Boolean literals used.

Another way that a Boolean literal is generated and used is with comparison operators. For example, the following sequence results in a Boolean literal of false, 0, or no for the c variable. (The > operator represents "greater than.")

var a=10;  var b=20;  var c=(a > b); 

The Boolean literal is automatically changed by JavaScript to a true/false, 1/0, or yes/no value, depending on the context. For example, the following little script uses the Boolean literal to generate a value much larger than 1:

<html>  <head>  <title> Boolean </title>  <script language="JavaScript">  var a=5;  var b=6;  var c=(a<b)  var d="Your stock is worth " +( c * 25 )+" thousand dollars.";  alert(d);  </script>  </head>  <body bgcolor="blanchedalmond">  </body>  </html>

Figure 3.2 shows the calculated output in JavaScript.

Figure 3.2. The output in the alert box has been formatted with the calculated results of the JavaScript program.

graphics/03fig02.gif

Whenever a result is true (1 or yes), JavaScript automatically looks at the context of the literal's use and makes the appropriate changes. Simply multiplying by 1 or 0 makes a huge difference because multiplying by 0 always results in 0. Sometimes, using tricks with Boolean values, you can save steps in your programs and do some interesting things that you would not be able to do otherwise.

Calculations and Concatenations

JavaScript numbers and strings sometimes share common operators, and others are used with numbers only. Chapter 4, "Using Operators and Expressions," covers all the operators and how they are used, but the basic arithmetic operators of addition, subtraction, multiplication, and division are +, -, *, and /, respectively. The plus sign (+) is used both for adding numbers and concatenating strings. String concatenation refers to binding one or more strings into a single string. For example, this returns New Riders:

var firstName="New";  var lastName="Riders";  var gap=" ";  var publisher=firstName + gap + lastName;  document.write(publisher); 

The plus sign (+) joins the three string variables firstName, lastName, and gap.

In addition to the basic math operators, JavaScript has both Math and Number objects for more complex operations and constants. Chapter 7, "Objects and Object Hierarchies," deals with these objects, but you should know of their availability for special number cases and complex math. The Math object has been employed in some of the examples where a conversion was required. For example, Math.floor( ) was used in Chapter 1 to convert the value of a form window into a number. All data entered into a text window are treated as text, so by using the Math.floor( ) function, it was possible to both round any value down to the nearest integer and convert it to a number. Elsewhere in this chapter, the toString( ) function changed a decimal value into a hexadecimal string representation.

Two important built-in functions may also be used for string and number conversions, parseFloat( ) and parseInt( ). The following script shows how these two different functions work.

parseString.html
<html>  <head>  <title> Parse them Strings! </title>  <script language="JavaScript">  var elStringo="14.95";  var laStringa="32 on sale";  var newVal=parseFloat(elStringo);  var hotVal=parseInt(laStringa);  document.write("Your total is: $" + (newVal+hotVal));  </script>  </head>  <body bgcolor="gainsboro">  </body>  </html>

Two strings containing numbers, elStringo and laStringa, are converted into numbers. The parseFloat( ) method takes both numbers and the first decimal and numbers beyond the first decimal. When it encounters a non-number after the first decimal point, it ignores characters and the function transforms the values to the left into a floating-point number. The parseInt( ) method parses numbers until the first non-number is encountered. Everything to the left of the first non-number is converted into a number. (Because all numbers in JavaScript are essentially floating-point numbers, the "integer" is simply a floating-point value with no decimal value other than zero.)

Objects as Literals

Objects are a collection of properties. While objects are discussed in detail in Chapter 7, you should understand that they can be treated as literals and placed into variables. In designing a dynamic web site, you can create the objects that you need in JavaScript and use them repeatedly on different pages. Think of objects as "design clusters" that can be placed where you need them.

As a collection of properties, objects can be used to create very useful tools and serve as the basis of object-oriented programming. To create an object, you first give it a name as a new object:

var shopCart = new Object(); 

When you have established your object, you can begin adding properties to it:

var shopCart.item = 5.95;  var shopCart.tax = .06;  var shopCart.shipping = 14.95; 

When making object literals, each property can be defined within curly braces, with the properties separated by commas. Each property is separated from its value by a colon.

The following shows a simple example of how to work with object literals:

var shopCart = { item: 5.95, tax: .07 , shipping: 14.95 }; 

The outcome is identical to the first set of object properties defined previously, but the format is different. Object literals, along with other characteristics and uses of objects, are revisited in Chapter 7 in more detail. For now, it is enough to understand that object literals constitute one of the data types in JavaScript.

Functions as Literals

Chapter 6, "Building and Calling Functions," covers functions in detail. In this section, the focus is on functions as a data type. Functions can be built-in or user-defined. A user-defined function has this form:

Function functionName(optional argument) { Commands, statements, definitions  } //function terminator 

Functions can be launched in different places in a program and serve as self-contained groupings of code to accomplish one or more tasks in a program.

However, JavaScript has the capability to include a function in a variable as a literal. For example, using the Base 16 conversion with the toString( ) method, it's possible to create a literal that converts decimal to hexadecimal. Base 16 is the name used for hexadecimal values. The decimal system is Base 10 because the number system is based on 10 characters, 0 9. Base 16 has 16 characters, 0 F. The following script changes three decimal values into a single hexadecimal value and slaps a # sign on the front to remind you that it's a hexadecimal value. The function named converter that does the conversion becomes a literal in a variable definition. The converter function runs three times to generate color values for the R, G, and B values.

functionLit.html
<html>  <head>  <title> Function Literal </title>  <script language="JavaScript">  function converter(decNum) {       if (decNum >=16) {             return decNum.toString(16);        } else {             return "0" + decNum.toString(16);        }  }  var colorIt="#" + (converter(255) + converter(108) + converter(4));  document.write(colorIt);  </script>  </head>  <body bgcolor="ghostwhite">  </body>  </html>Objects

You can never have too many decimal-to-hexadecimal conversion scripts. Compare the previous conversion script with the one in Chapter 1. All the decimal input for the one in this chapter is in the script, and all the data use functions as literals.

Undefined and Null Values

Two other types of data, null and undefined, should help you better understand a little about how JavaScript deals with variables. Both generally signal something that you forgot to do, but sometimes they are a planned part of a script.

An undefined value is returned when you attempt to use a variable that has not been defined or one that is declared but that you forgot to provide with a value. A nonexistent property of an object also returns undefined if it is addressed.

On the other hand, null amounts to a "nothing literal." You can declare and define a variable as null if you want absolutely nothing in it but you don't want it to be undefined. Null is not the same as zero (0) in JavaScript. In some situations, you will want to find the result of a calculation, which could be zero; rather than putting in a zero to begin with, you can place a null in a variable. In that way, when data does come into a variable, you will know that the value is part of the calculation and not a default zero that you placed there. The following little script shows the different outcomes when a variable is undefined and when it is null.

nullUndef.html
<html>  <head>  <title> Null and Undefined </title>  <script language="JavaScript">  var nada;  var noVal=null;  document.write("<b>No value assigned and the variable is " + nada + ".<p>" );  document.write("A null value was assigned and returns " + noVal + ".</b>");  </script>  </head>  <body bgcolor=#BadCab>  </body>  </html>

Regular Expression Literals

Regular expression (RE) literals are advanced programming concepts and constitute almost a whole new language. In fact, learning the regular expression nomenclature will prepare you for much of Perl. (Chapter 16, " CGI and Perl," covers working with JavaScript, CGI, and Perl.) The easy part of regular expression literals is that they are identified by slashes (/), as strings are with quote marks. The following are some examples of RE literals:

/do/  /[a-k]/  /[^l-z]/ 

The meaning of the RE literals is another matter. Typically, RE literals are used with sequences or groups. Groups are placed in brackets ([]), and sequences are indicated by a dash (-). For example, a group of letters that you might want to match might be l, k, and r. Any one of these letters would be recognized if placed into a class /[lkr]/, while a word such as fun would be patterned as /fun/ in an RE literal. (A class in regular expressions refers to a group of characters to match.) A range of characters or digits would be placed in a pattern such as /[b-s]/ or /[5-9]/. Anything that you don't want is prefaced by a caret (^), as in /^blink/.

For the designer, regular expressions are important for searching for different elements of strings. If your design requires finding keywords entered by customers looking for certain products, you could use regular expressions to search for the product and provide feedback to the customer about whether it is available.

An example of an RE literal can be seen in a global replacement of one word for another in the following script.

regExp.html
<html>  <head>  <title> Regular Expression Literal </title>  <script language="JavaScript">  var work="Working with JavaScript is hard work but rewarding work.";  var play=work.replace(/work/gi, "play"); //Regular expression  document.write("<p><b>" + work + "<p>" + play);</script>  </head>  <body bgcolor="navajowhite">  </body>  </html>

The RE literal work.replace(/work/gi, "play"); commanded the variable named work to have all instances of the word work (/ work/) be globally (g) replaced, ignoring case (i), by the word play. The output for the script is shown in Figure 3.3.

Figure 3.3. Using regular expressions in variables, parts of a string can be changed.

graphics/03fig03.gif

Because cases are being ignored, "Working" becomes "playing." Otherwise, the variable containing the RE literal simply took the first string and replaced it with the second following the rules of regular expressions.

In Chapter 16, you will revisit regular expressions in Perl and see how JavaScript can use regular expressions themselves in dealing with data in a CGI bin.

Variables

If you have been following the book sequentially, by this point, you probably have a pretty good idea what a variable is from all of the examples. You've been provided with several of the rules for providing names and values for variables as well. This section examines variables in detail and spells out what you can do with them and how to use them.

I like to think of variables as containers on a container ship. You can put all different types of content into the containers, move them to another port, empty them, and then replace the container with new content. However, the container ship analogy suffers when you realize that the content in the containers must have magical properties. If you have a container full of numbers and you add a string, the whole container magically becomes a string. Because JavaScript is untyped (or weakly typed), both the contents and the characteristics of the variable can change. The main point, though, for readers new to the concept of a variable is that variables are containers with changeable contents.

Declaring and Naming

JavaScript, like most scripting languages, has two basic ways of declaring a variable. First, as you have seen throughout the book up to this point, variables are declared using the var word. You simply type in var followed by a variable name and value. The following are typical examples:

  1. var item;

  2. var price= 33.44;

  3. var wholeThing= 86.45 + (20 *7);

  4. var name="Willie B. Goode";

  5. var address "123 Elm Street";

  6. var subTotal=sumItems

  7. var mixString= 11.86 + "Toy Cats";

  8. var test = (alpha > beta)

By taking each variable one at a time, you can see how the different data types discussed are placed into a variable:

  1. The first example demonstrates that you can declare a variable but not give it a value. As you saw previously in this chapter, such variables have an undefined value.

  2. The second variable contains simple primitive data a numeric literal with a value of 33.44.

  3. The third variable is a compound variable made up of a numeric primitive and a compound expression.

  4. The fourth variable is defined as a simple string literal.

  5. The fifth variable is also a simple string literal, but it uses a mix of digits and letters.

  6. Sixth, the variable is defined with another variable.

  7. The seventh variable is a mix of a numeric primitive and a string primitive, creating a string variable.

  8. Finally, the last variable is a Boolean value derived from compound data.

Declaring a variable alerts the computer to the fact that a new variable is available to use. After a variable is declared, it need not be declared again. For example, in loop structures, the counter variable can be defined in the initialize section, but not in the test or change (increment/decrement) sections. For example, the following code segment shows that the variable named counter is declared in the first segment but then is not declared again:

for (var counter=0; counter < 40; counter++) {.... 

Some programmers like to initialize all of their variables at the beginning of a script with undefined values. Then later they can use them without having to remember to add var. Also, you can have a single line with several variable definitions, with each variable separated by a comma or a semicolon, as the following script illustrates.

clutter.html
<html>  <head>  <script language="JavaScript">  var a=20; b=30, c="wacka wacka do"; gap=" ";  document.write(a+ gap + b + gap +c);  </script>  <body bgcolor=#C0FFEE>  </body>  </html>

I generally avoid declaring more than a single variable on a line. Multiple declarations in a line, while workable, can clutter what has been defined and what a variable has been defined as. The script clutter.html amply illustrates such confusion. (By the way, the character following the c in the bgcolor value is a zero, [0], not a capital O.)

You may omit the var keyword in your variable declarations, and you undoubtedly will see scripts in which the programmers have done so. For example, the following are perfectly good examples of such declarations:

acme = "The Best";  cost = 23.22; 

While JavaScript accepts these declarations for global variables, you can run into problems elsewhere by omitting var. (See the note in the following section.) Thus, for a good programming habit that will avoid problems, always use the var keyword when declaring a variable.

Global and Local Variables

Variables in JavaScript have scope. The scope refers to the regions of the script where the variables can be used. A global variable, as the name implies, has global scope and is defined in the entire script. Local variables are local to the functions in which they are defined. As a general rule, avoid naming any two variables, whether local or global, with the same name or identifier.

NOTE

While using the keyword var is optional in declaring global variables, problems can arise if you do not incorporate var in defining your local variables. When using var in a local variable declaration, the program recognizes it as a local variable, not a change in the value of a global variable. With no var keyword used, your script cannot tell the difference, and you risk inadvertently changing the value of a global variable. The moral to this story is to always use the var keyword for variable declaration.

Within a function, a local variable has precedence over a global variable of the same name. So, if your global variable named ID has the value Fred, and a function also with a variable named ID has a value of Ethel, the name Ethel will appear when the function displays the variable's value. However, if you display the value of the ID variable from outside the function, the value will be Fred.

The following script uses four variables to demonstrate these differences. Two global variables are defined, and then two local variables are defined within a function. One of the global and local variables share a common identifier, localGlobal. When fired from the function, the local variable's value is displayed; when displayed from the global script, the global variable's value is displayed.

GlobalLocal.html
<html>  <head>  <script language="JavaScript">  var onlyGlobal="This variable is only global!";  var localGlobal ="I\'m global now!";        function showMe( ) {            var localGlobal="I\'m now local";             var onlyLocal="Only works on the local level."             alert(localGlobal + " -- " + onlyLocal);             }  showMe( );  document.write(onlyGlobal + "<p>"+ localGlobal);  alert(onlyGlobal);  </script>  <body bgcolor=#CadDad>  </body>  </html>

Figure 3.4 shows what your page will look like the second time you open it. Initially, you will see only a blank page with the alert box, but after the second alert, you can see both the values from the local and global variables on the screen simultaneously.

Figure 3.4. Global and local variables of the same name can return different values.

graphics/03fig04.gif

In Chapter 6, where functions are discussed in detail, you will learn how to maximize the use of global and local variables in functions. In the meantime, just remember to keep everything between the two types of variables straight by using the var keyword in all your variable declarations.

Primitive and Compound Data

Data types are divided into two basic categories, primitive and compound. Boolean values, numbers, strings, and the null and undefined values all constitute primitive data types. As you have seen, different data types are handled differently.

Compound data types are made up of more than one component. Two primitive data types, such as 10 multiplied by 7, can make up compound data. Compound data can have components made up of other compound data, made up of other compound data, ad infinitum. Compound data can mix and match different data types as well.

In addition to a multiple of primitives, compound data are made up of arrays and objects. By definition, arrays and objects are made up of more than one object. Arrays are a collection of elements, and objects are a collection of properties. JavaScript objects are discussed in detail in Chapter 7, and arrays are examined at the end of this chapter.

In storing the two different data types, JavaScript uses two very different strategies. Primitives are stored in a fixed chunk of memory, depending on the type of primitive data. Because a Boolean literal is either true or false (1 or 0), a Boolean can be stored in a single bit, while a number can take up several bytes. What is important is that primitives have a finite and known amount of space in memory and can be stored with the variables.

Compounds, on the other hand, can get quite complex, as is the case with objects, regular expressions, and functions. Rather than having a space in memory for compound variable values, JavaScript has pointers or references to the values. In other words, the variables themselves are made up of directions to locate their value rather than the actual value.

Calling strings "primitives" can be a bit misleading because they are obviously anything but fixed in size. They are considered immutable, meaning that the string value cannot be changed. So, if the value of a string cannot be changed, how can a variable with the value Tom be changed to a value Jerry ? Obviously, a pointer has to point to the changed value, but strings act like primitives; therefore, I treat them as primitives.

Arrays

Because objects are collections of properties with each property having its own name and value, arrays are actually JavaScript objects. Each property in an array is an element, and each element can be assigned a value. One way to think of an array is as a collection of numbered variables.

An array in JavaScript has the following general formats for assigning values to elements:

sampleArr[0]=1;  sampleArr[1]="ice cream";  sampleArr[2]=55 * (7 + alpha);  sampleArr[3]= shootTheMoon(73);  sampleArr[4]= otherArr[7]; 

or

sampleArr=new Array(1,"ice cream", (55 * (7+ alpha)), shootTheMoon(73),  otherArr[17]); 

or, in JavaScript 1.2 or later:

sampleArr=[1,"ice cream", (55 * (7+ alpha)), shootTheMoon(73), otherArr[17]]; 

All three arrays are identical, using different methods for data assignment. The second two methods show the array to be more of an object, while the first method shows the variable-like characteristics of arrays.

In JavaScript, array elements begin with 0 and can be numbered sequentially or nonsequentially. In the second two previous examples, the first element is 0, and the other data separated by commas are numbered sequentially. However, you could have the following data assignment in an array:

alphaArr[0]= "uno";  alphaArr[7]= "dos";  alphaArr[345]= "tres"; 

Usually, arrays are numbered sequentially so that data can be added and extracted using loops. However, an array element can be called forth in any order and used just like a variable.

The data and data types that can be assigned to an array element are identical to the data and data types that you can assign to variables. You will also find that you can assign objects the same kinds of data. (Remember that an array is an object because it is composed for more than a single property.)

Setting Up an Array

Arrays are created using a constructor, just like other objects. The Array( ) constructor uses the following format:

var parts = new Array( );

Now, parts is an array object, and you can add data as in the following format:

parts[0]= "bolts";  parts[1] = "nuts"; 

As with declaring a variable, you need not enter data upon declaring the array, but you can. For example, you may declare and define a dense array using the Array( ) constructor:

var parts = new Array("bolts", "nuts", "washers", "screws"); 

You can also create an array using a dimension argument. If you know ahead of time how many elements are in your array, you can declare it and set a dimension for it at the same time. (In some languages, especially older ones, you are required to include a dimension for an array to reserve memory for your array.) For example, if you are creating an array of the U.S. Senate and you know that you have only 100 senators, you could declare and dimension your array as follows:

var senators= new Array(100); 

Once declared and dimensioned, you can add 100 elements, but the first senator would be this:

senators[0] 

The last would be this:

senators[99] 

You still get 100 elements, but you must begin with 0 instead of 1.

The declaration using a dimension argument is the exception to the rule that the first data value in a dense array (one in which the data are contained in parentheses) is considered element 0. Element 0 in the array will be the first data assignment after the declaration. For example, the following declaration first dimensions the array at 5 and then enters the first array element (0) as 7 in the next line:

var catWeights= new Array(5);  catWeights(7,15,34,52,60); 

The numeric data value 5 is not a value of any of the array elements. It is the length of the array, with elements ranging from 0 4.

NOTE

Throughout the book, I use the tag <script language="JavaScript"> without specifying the version number of JavaScript. You do not need to specify the version number to get the latest version of JavaScript supported by your browser. When using a dimension argument with Netscape Navigator 4 (NN4) and later, you will run into a bug if you specify <script language="JavaScript1.2"> and then attempt to dimension an array. NN4+ treats the declaration with the dimension value as the first value in the array instead of the length of the array. For example, try the following script:

<html>  <head>  <script language="JavaScript1.2">  var test= new Array(23)  document.write(test.length);  </script>  </head>  <body>  </body>  </html>

When you run the script using NN4 or later, a 1 appears on the screen. If you remove the 1.2 attribute from the <script> tag, the returned value is 23, the correct length. Because JavaScript 1.5 runs just dandy in Netscape Navigator 6 without specifying the version number in the <script> tag, and the latest version for Internet Explorer also runs well without specifying the version number, I prefer to leave out all version numbers as a habit. In this way, I can avoid bugs and span more JavaScript and browser versions.

A final way to declare an array using JavaScript 1.2 or later is called an array literal. The declaration uses brackets instead of parentheses and does not require the Array( ) constructor. The array object name is declared simply by assigning values to it within brackets, as the following script shows:

<html>  <head>  <script language="JavaScript">  var Lit= ["yes","no","maybe"];  document.write(Lit[2]);  </script>  </head>  <body bgcolor=#face00>  </body>  </html>

The literal array Lit looks almost like a variable definition, were it not for the bracketed list of values. Using an array literal saves a couple of steps because no constructor is used, but older browsers (those before support of JavaScript 1.2) will not understand it as an array.

Array Properties and Methods

As an object, arrays have a single property, length, and several methods. However, Netscape Navigator 4 introduced five methods, Array.pop(), Array.push( ), Array.shift( ), Array.unshift( ), and Array.splice( ), that are not supported either by Internet Explorer or the EMCA-262 standard. To avoid problems but to be inclusive, I have placed the NN4+ array methods in a section at the end of the chapter to alert you to the fact that users of IE will not parse them correctly. Like all JavaScript enhancements not supported by the EMCA standards, I do not recommend using these methods for creating web sites that expect to have viewers using both major browsers.

Array Length

The single array property length returns the number of elements in an array. When using a loop, the test condition for the loop can be the length of the array so that you need not use an invariant value for the test. The format is as follows:

Array.length

The property is easily passed to a variable, as the following sample shows:

var dogs = new Array("Beagle","Terrier","Collie","Mutt");  var dogTail= dogs.length; 

The variable dogTail would have a length of 4 because four elements make up the array. The length property does not refer to the number of characters that make up the element in the array, but it refers to the number of elements themselves. Thus, the following array has a length of 2, even though more characters are used than in the first example with a length of 4:

var dogs = new Array("Greater Swiss Mountain Dog","Irish Wolfhound");
Concatenating the Elements of an Array: join(), toString(), and concat()

The Array.join( ) method takes all of the values in all of the elements in the array and creates one big string. For example, try out the following script:

joinArray.html
<html>  <head>  <script language="JavaScript">  var trees= new Array("Elm","Pine","Oak");  var bigBush=trees.join( );  document.write(bigBush);  </script>  </head>  <body bgcolor=#ace007>  </body>  </html>

The results are the contents of the array minus the quotation marks, showing you Elm,Pine,Oak.

The Array.join( ) method accepts an argument that acts as a separator. Whatever you place in the join( ) parentheses within quotation marks replaces the commas. For example, change this line:

var bigBush=trees.join( ); 

to

var bigBush=trees.join(" and "); 

Then, launch the script again for a different result. The second results are Elm and Pine and Oak.

An older method from JavaScript 1.1 that is similar to the Array.join( ) method is Array.toString( ). The toString( ) method generates the same results as join( ), but you cannot specify the connecting characters between elements as you can with join().

A third method used for concatenating string elements in arrays is Array.concat(). Not only does the concat() method join all existing elements, but it also adds the elements in a concat() argument. For example, by changing the joinArray.html script slightly, you can see how it works.

concatArray.html
<html>  <head>  <script language="JavaScript">  var trees= new Array("Elm","Pine","Oak");  var biggerBush=trees.concat("Maple", "Sycamore");  var bigBush=trees.join();  document.write(biggerBush);  alert(bigBush);  </script>  </head>  <body bgcolor=#ace007>  </body>  </html>

A very important part of the concatArray.html script is that you can see that the Array.concat() method does not change the contents of the array. The array named trees still has only three elements. That is evidenced by the fact that the alert message shows only three elements, even though the variable bigBush was defined after the biggerBush variable was defined and added the Maple and Sycamore data to the mix. To add elements to an array, you assign new values to named elements. For example, to include the Maple and Sycamore data to the array, you could write this:

trees[3]="Maple"; // The fourth element is 3 since the first is 0  trees[4]="Sycamore";
Changing the Order of an Array: sort() and reverse()

Two methods are available to change the order of array elements. The first sorts the array string elements alphabetically, and the second reverses their order.

The Array.sort() method is very simple, especially when using strings. After entering all of the strings in the array, you just enter the name of the array and method, and the array is ordered alphabetically. The following example shows both how the sort() method works and how array elements are extracted with a loop statement.

sortArray.html
<html>  <head>  <script language="JavaScript">  var zoo= new Array("zebras","lions", "apes","tigers");  zoo.sort( );  var newZoo="";  for(var counter=0; counter<zoo.length; counter++) { newZoo += (zoo[counter] + "<br>") ;  }  document.write("<p>Alphabetical Animals<p>" + newZoo);  </script>  </head>  <body bgcolor="lightsteelblue">  </body>  </html>

As you can see in Figure 3.5, all of the values are arranged in alphabetical order.

Figure 3.5. By placing string data into an array, you can easily sort it using the Array.sort( ) method.

graphics/03fig05.gif

apes

lions

tigers

zebras

For ordering lists of any kind, you will find the Array.sort( ) method a handy tool.

The Array.reverse( ) method simply reverses the order of the data in the array. The first element becomes the last element, and everything else in the array is reversed as well. For example, the following:

var majorCities=new Array("Tokyo", "Los Angeles", "Paris", "Beijing", "Bloomfield")  marjorCities.reverse( ); 

would return this:

Bloomfield, Beijing, Paris, Los Angeles, Tokyo

By using Array.sort( ) and Array.reverse( ) in concert, you can change ascending and descending orders of a sorted list.

Extracting Subarrays: slice()

To specify a subarray, use Array.slice( ). The general form of using slice( ) is shown here:

ArrayName.slice(begin,end) 

or

ArrayName.slice(begin to end) 

For example, if you have these statements:

computer=["Dell", "Gateway","Apple","IBM","HP"];  computer.slice(2,4); 

your return would be

Apple,IBM

Using a single argument takes the element from the argument to the end of the array as defined by the argument. For example:

computer.slice(2); 

would return

Apple,IBM,HP,

Negative numbers constitute a final type of argument used in the Array.slice( ) method. The negative value begins with the last element in the array as 1 and then counts backward toward the first element. For instance, the statement from the example in this section:

computer.slice(-1) 

returns this:

HP

Unlike the forward-counting slices that begin with 0, the last element in an array is identified as 1 using the slice( ) method with an array.

Navigator 4 Core Array Methods: pop(), push(), shift(), unshift(), splice()

This last set of methods adds a good deal of utility to working with arrays, and you can perform stack-like operations with the array. If you've ever written programs in Forth or written code for Adobe PostScript, you've worked with the stack, and pop( ) and push( ) are familiar. Each of the five is described briefly with a short explanation and is based on the following single example:

var stackWork= new Array("Lenny","Harold","Mary","Jean", "Sal");

Array.pop( ) removes the last element of an array and returns it.

stackWork.pop( ); returns Sal and removes it from the array. If a second identical statement were made on the next line, it would return Jean.

Array.push( ) adds a value to the end of the array (top of the stack) and leaves it there. By adding the following line, the string Delia would become the value to a new last element added to the array by the push( ) method:

stackWork.push("Delia"); 

In a pop( ) operation, it would be the first one off (LIFO last in, first off).

Array.shift( ) removes the first element in an array and returns it. For example, this would return Lenny, remove it from the array, and shift the remaining elements to the left:

stackWork.shift( ); 

Element 0 would become Harold.

Array.unshift( ) is similar to the push( ) method, except that the new element is put at the front of the array (bottom of the stack). If you entered the following, the first element (element 0) in the array would have a value of Willie, the value Lenny would be shifted to the right into element 1, and so on for the entire array:

stackWork.unshift("Willie"); 

Finally, Array.splice( ) is a method used to insert, delete, and substitute values in array elements. The method has three arguments, start, delete, and data. The starting position specifies where the new value (data) is to be inserted and where deletions begin. If no deletions are specified, the splice( ) method has the effect of inserting an element and value into an array. For example, the following shows how to insert the value Fred into the second element, leaving the first as it is and shifting the rest to the right:

stackWork.splice(1,0,"Fred"); 

The splice( ) method allows you to insert elements, delete one or more elements, or change the value of an array element. You might find that these functions do not work in some of the older browsers, but IE5+ and NN4+ work well with them.

Summary

This chapter examined both the data types and the containers for data in JavaScript. An understanding of data types and variables in JavaScript is essential to working effectively with JavaScript because changes in the properties and objects that make up JavaScript and HTML are dependent on controlling the values in variables. Because the values are the data, all of the work with objects depends on understanding how to use the data types and their containers, variables.

In addition, array objects, along with the property and methods associated with arrays, were introduced. Each element of an array has variable-like characteristics, but an array is a very different breed of animal. With an object, the web designer can use the built-in property and methods to order and change the array elements. In further chapters, as more structures in JavaScript are revealed, you will see far more applications for and the value of arrays.

CONTENTS


JavaScript Design
JavaScript Design
ISBN: 0735711674
EAN: 2147483647
Year: 2001
Pages: 25

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