time you finish Sams Teach Yourself J2EE in 21 Days, you should have the After the servlet or JSP has order of a few minutes—half an hour at most. JavaScript in 24 Hours, Sams Teach Yourself, - Ebook download as PDF File .pdf), Text File .txt) or read book online. vi sams teach yourself java in 24 hours, sixth edition hour sams teach yourself free download here sams teach yourself java jsp in 21 days 3.

Sams Teach Yourself Jsp In 24 Hours Pdf

Language:English, French, German
Published (Last):22.05.2015
ePub File Size:22.45 MB
PDF File Size:16.66 MB
Distribution:Free* [*Sign up for free]
Uploaded by: BOOKER

D:\BIBLIOTECA\Java\Enterprise\[ SUN] Java EE5 D:\ BIBLIOTECA\Java\Enterprise\Teach Yourself J2EE in 21 D:\ BIBLIOTECA\Java\Enterprise\AS\JBoss4\[ Sams] JBoss The Official . Teach Yourself JSP with Apache Tomcat in 24 Indexer Sams teach yourself Ajax, JavaScript, and PHP all in one / Phil Ken He wrote Sams Teach Yourself JavaScript in 24 Hours and has also written are more comfortable with ASP, JSP, or some other server-side Way language. jsp:fallback>, jsp:file>, PDF jsp:forward>, jsp:import>, jsp:include>, , jsp:params>, jsp:text>, jsp:useBean>.

Rarely does a technical book do all four of these things. Read, learn, and live the lessons in this book and you can accurately call yourself a software professional.

The Clean Coder is much more than a set of rules or guidelines. It contains hardearned wisdom and knowledge that is normally obtained through many years of trial and error or by working as an apprentice to a master craftsman.

If you call yourself a software professional, you need this book. Hence I have tried to give references that will both illuminate particular points and guide the interested reader to other useful works. Many friends have read the manuscript and some have prepared extensive helpful comments; where these seemed valuable but did not fit the flow of the text, I have included them in the notes. The output as written to the page looks like this: Rounding The methods ceil. As Math. In other words.

The youngest person is 19 years old The oldest person is 31 years old Random Numbers To generate a random number. They are listed in Table 4. Caution You always use Math methods directly. Mathematical Constants Various often-used mathematical constants are available as properties of Math.

The code would provoke a JavaScript error. Normally we like to specify the possible range of our random numbers. Instead you simply need Math. The keyword with takes an object as an argument. The statements within that code block can call methods without specifying an object.

Reading the Date and Time We put into practice some of what we covered in this hour by creating a script to get the current date and time when the page is loaded.

We also implement a. By using with you can save yourself some tedious typing. Take a look at Listing 4. As we do so. As you will recall. We can access the individual parts of the time and date using getDate. Remember that JavaScript counts months starting at 0 January and ending in 11 December. At that point the script runs again. Note that the month is displayed as 0.

You can retrieve the difference between your local time and UTC time by using the getTimezoneOffset method. You worked with browser information from the navigator object.. You learned how to select page elements by their ID using the document. Does Date have methods to deal with time zones? In addition to the get.

See Appendix B for a full list of methods. You should use getFullYear and setFullYear instead. The methods getYear and setYear do exist. Which method of the Math object always rounds a number up to the next integer?

What happens when a user clicks OK in a confirm dialog? A value of true is returned when OK is clicked. A value of true is returned to the calling program. Because of the potential problems with dates spanning the millennium.

The dialog is cleared and control is returned to the calling program. The location. The displayed message is returned to the calling program. If my loaded page is http: Exercises Modify Listing 4.

Use the history object to create a few pages with their own Forward and Back buttons. The volume returned should be rounded up to the nearest cubic meter. In this hour you learn about the JavaScript data types of number.

To express numbers falling between the integers. In JavaScript. Numbers Mathematicians have all sorts of names for different types of numbers. The numeric and string data types supported by JavaScript Conversion between data types How to manipulate strings We use the term data type to talk about the nature of the data that a variable contains.

Later you can use it as a string again. From the socalled natural numbers 1. JavaScript supports both integer and floating-point numbers. We also mention escape sequences in strings. Hour 5. A string variable contains a string. If you put a string into your variable and later want to interpret that value as a number. All of the following are valid integers: Hexadecimal numbers begin with 0x. All the following are valid floating-point numbers: Note In exponential notation.

To put it another way.

They can be represented in the traditional way. An integer is a whole number—positive. Not a Number NaN NaN is the value returned when your script tries to treat something non-numerical as a number. Exponential notation provides a compact way to express numbers from the very large to the very small. You can test for non-numerical values with the isNaN function: If the first character in the specified string is a number. The parseFloat function parses a string and returns a floating-point number.

Using parseFloat and parseInt JavaScript offers us two functions with which we can force the conversion of a string into a number format. In most JavaScript implementations. Click here to view code image parseInt You can test for infinite values with the isFinite function. Click here to view code image parseFloat " The isFinite function takes the value to test as an argument and tries to convert that argument into a number.

False and true are known as Boolean values. There is also the keyword literal -Infinity to signify the negative infinity. This function allows us to optionally include. If the result is NaN. Click here to view code image isFinite Click here to view code image isNaN 3. You can define an empty string by using two quote marks with nothing between them: Examples include the tab character. To use such a character in a string.

Strings A string is a sequence of characters from within a given character set for example. The result of inserting these escape sequences is shown in Figure 5. You define a string by enclosing it in single or double quotes: Escape Sequences Some characters that you want to put in a string may not have associated keys on the keyboard. Such a combination is known as an escape sequence. This is known as string concatenation.

TABLE 5. The first is the starting index—substr extracts the characters from a string. The method returns the index the position of the searched-for substring. The second parameter number of characters is optional. JavaScript automatically converts true to 1 and false to 0. In the example. It works the other way. JavaScript interprets any nonzero value as true.

JavaScript interprets all of the following values as false: In a practical application. The Negation Operator! JavaScript interprets the! A new dialog will open. Figure 5. Summary In this hour. Normally you assign the value null to something when you want it to have a valid but nonexistent value.

It is a predefined global variable used to store the value of a variable whose name has been used in a statement. For certain implementations. What statement would return a new string created by appending one string called string2 to another string called string1?

The JavaScript Specification does not specify a maximum string length. JavaScript also has two keywords called object literals—null and undefined. This means that it is not zero or null.

To do this in JavaScript. Which statement sets the value of variable paid to Boolean true? What is the maximum length of a string in JavaScript? Does JavaScript have a data type to represent a single character? For a numeric value.

Unlike null. Boolean values should not be enclosed in quotes. Write a JavaScript function to capitalize the first letter of each word in a given string.

JavaScript in 24 Hours, Sams Teach Yourself, 6e.pdf

Exercises Write a JavaScript function to remove a given number of characters from the end of a string. Hour 6. Each value has a numeric index that may contain data of any data type—Booleans. JavaScript has the array data type to help you do this. Arrays An array is a type of object used for storing multiple values in a single variable. Creating a New Array The syntax used for creating an array will already be familiar to you.

What we mean by the array data type How to declare and populate arrays How to manage array contents Sometimes it makes sense to store multiple variable values under a single variable name. Initializing an Array You can optionally preload data into your array at the time it is created: The following code returns the length of the preceding array: Array Methods Caution Some of the array methods have the same name—and almost the same function— as string methods of the same name.

Be aware of what data type you are working with. TABLE 6. The length property is automatically updated when you add items to or remove items from the array.

Suppose we add a new item to the preceding array: Table 6. Click here to view code image myArray. The method returns the index of the searched-for element. Wednesday indexOf We can use indexOf to find the first place where a particular element occurs in an array.

The first element sets the location in the array where we want to perform the splice. Caution Using splice changes the original array! If you need to preserve the array for use elsewhere in your code.

In your text editor. Click here to view code image myWeek. The syntax is a little more complex than that of the previous examples: Click here to view code image array. The method returns any removed elements. We next apply the splice array method to the words array.

Since the splice method. The method returns an array of elements. We store that array in the variable words. In this hour. Since we supply a single space as the argument to join. The wrangleArray function is called by a small script in the body of the document: What value will be returned by indexOf if it is passed a value that does not appear in the array to which it is applied?

Exercise Review the array and string methods that share a method name. If the element with highest index in array Foo is Foo[8]. JavaScript does not directly support associative arrays arrays with named indexes. Familiarize yourself with how the syntax and operation changes depending on whether these methods are applied to a string or an array.


You have an array called monthNames containing the names of all the months of the year. You can create an array of arrays. How would you use join to create a string name containing all of these month names with a single space between names? You see examples of this later in the book. Does JavaScript allow associative arrays? It will return Can I create a multidimensional array in JavaScript?

To create anything but the simplest scripts. First we declare a variable message. Using conditional statements Comparing values with comparison operators Applying logical operators Writing loops and control structures Setting Timers in JavaScript In Hour 5. The if Statement In the previous hour we discussed Boolean variables. In this hour we examine ways to recognize particular conditions and have our program act in a prescribed way as a result.

JavaScript supports various such conditional statements. JavaScript has several ways to test such values. The third statement tests the value of the variable bool to see whether it is true. Conditional Statements Conditional statements. We then declare a new variable. It has the following general form: Click here to view code image if this condition is true then do this.

Hour 7. Some of the comparison operators are listed in Table 7. Comparison Operators The if statement is not limited to testing the value of a Boolean variable. Had we assigned a value of false to bool in the second line. TABLE 7. We can test for the Boolean value false by using the negation character! Click here to view code image if! In the case of a Boolean value. Click here to view code image if input.

Now you can further develop that function using the if statement. Now we can see that. Listing 7. Create this file in your editor. Note A more comprehensive list of comparison operators appears in Appendix B. JavaScript has an operator. Were we to use this statement. For example: Caution If you need to test whether two items are equal both in value and in type. To achieve this we use the else construct: Click here to view code image condition is true?

What if we want to do more than this.. If the value in count is 0 or a number greater than 1. Pass only with great care". If break is omitted. The keyword switch has in parentheses the name of the variable to be tested. The tests themselves are listed within the braces.

This jumps us to the end of the switch statement after having executed the code for a matching case. Each case statement with its value in quotes is followed by a colon. There can be any number of code statements in each section. Logical Operators There will be occasions when we want to test a combination of criteria to determine whether a test condition has been met. Depending on the result of the test performed on the data.

Note the break statement after each case. The optional default case has its code executed if none of the specified cases were matched. There are many occasions. If the number of repeats is fixed. The only difference is that. All the time the condition keeps coming up true. JavaScript has various built-in loop structures that allow us to achieve such goals. Each time while evaluates the condition as true.. When count has been decremented to zero. By this time.

Click here to view code image var count. The statements in a do. Have a look at the syntax: With the for loop. As in the previous example. Caution Beware accidentally creating an infinite loop. The break command works within a loop pretty much as it does in a switch statement—it kicks us out of the loop and returns operation to the line of code immediately after the closing brace. Now every time while tests the variable count.

Looping Through Objects with for. We saw previously that. An infinite loop can stop the browser from responding. The loop will occur once for every property of the supplied object in our example. You can use the for. The result of running this example is shown in Figure 7. To help you. This is especially common when writing user interface routines. JavaScript provides two useful methods. You can use it. If later you want to cancel the timer function.

You can use the one you feel most comfortable with. Is there a way to stop the current trip around a loop and move straight to the next iteration? Like setTimeout. Is there any particular reason why I should use one sort of loop over another? Summary In this hour you learned a lot about testing conditions and controlling program flow based on the values of variables.

You also learned a little about using timers in your programs. The setInterval action. It works pretty much like break. Exercises In Hour 4. The break command ends loop execution. How can you modify the code to list the months starting with January as Month 1 rather than Month 0? There are too many statements in the loop.

The condition to terminate the loop is never met. Modify Listing 7. An infinite loop occurs if the condition to terminate the loop is never met. Which of the following is likely to cause an infinite loop to occur? The wrong sort of loop has been used. What command forces the cancellation of a loop. Write a program using a switch statement to output a different message to the user. You might design a general-purpose object called Car.

What object-oriented programming is Two ways to create objects Instantiating an object Extending and inheriting objects using prototype Accessing object methods and properties Using feature detection As your programs become more complex. Procedural programming is characterized by having data stored in variables.

For each car in the rental fleet. In object-oriented programming OOP. Hour 8. What Is Object-Oriented Programming? The code examples to date have been so-called procedural programming. Each instruction or list of instructions.

The Car object would have certain properties color. In this hour you learn the basics of object-oriented programming OOP. Using inheritance. We could easily fill the whole book with theory and practice of OOP. Providing they adhere to these rules. You learn about constructor functions during this hour.

For objects. Inheritance—Often when coding you will have a need for some code that is nearly. OOP allows you to reuse your code in a variety of scripts. JavaScript is not one of these. In the previous hours you often used objects. You could achieve this with regular functions. Writing OOP code offers several advantages over procedural methods: Code reuse—First. Object Creation. You can also easily add a method to the object too.

Create a Direct Instance JavaScript has a built-in object simply called Object that you can use as a kind of blank canvas for creating your own objects: You do so because you are trying to assign to method newObject. Using the this Keyword. You can begin to rectify that by adding a property: Click here to view code image myNewObject. To call the new method.

For the moment. Now your object owns a property—in this case a text string containing some information about the object and called info. Caution Notice that you use just the name of the function here without the parentheses. Had you used the code Click here to view code image myNewObject. JavaScript offers several ways to create an object.

The window object does not have a property called info. In the context of the showInfo method. You may recall that you used such a keyword in Hour 2. Upon the first declaration of the function myFunc. Note the use of the this keyword in the previous function definition. When you use this inside a function or method.

Loading this page into your browser. Clicking on the first button makes a call to the showInfo method of the newly created object: Instead of this code: JavaScript reports an error.

A better way to create objects that will have multiple instances is by using an object constructor function. By using similar assignment statements you can add as many properties and methods as you need to your instantiated object. Tip An object with only one global instance is sometimes called a singleton object.

URL of last page viewed.

Take a look at the following code. These objects are useful sometimes. Instead of using new Object. Tip JavaScript offers a further way to create a direct instance of an object.

Having defined your constructor function. You can examine the value stored in the info property for each object by clicking on. The code in Listing 8. The setInfo method takes an argument. Two instances of the object are instantiated. Now you can call its methods and examine its properties: Instantiating an Object You can now create as many instances as you want of this object type.

In doing so. All will have the properties and methods defined in the myObjectType function. Creating an object instance is known as instantiating an object. Note Note that this syntax is identical to using new Object. In the following code. This overwrites the value stored in the info property of object myNewObject2. As you instantiate two objects. A third button calls the setInfo method of object myNewObject2.

The revised values can be checked by once again using Show Info 1 and Show Info 2. Extending Objects What if you want to extend your objects with new methods and properties after the objects have already been instantiated? You can do so using the keyword prototype. Tip You can define the constructor function to accept as many or as few arguments as you want: Click here to view code image function Car Color.

The prototype object allows you to quickly add a property or method that is then available for all instances of the object. Click here to view code image Person. Extending and Inheriting Objects Using prototype A major advantage of using objects is the capability to reuse already written code in a new context.

These techniques are known. Within the constructor. You can also omit the semicolon if you start a new line after the statement. If you combine statements into a single line, you must use semicolons to separate them. Functions provide a simple way to handle a task, such as adding output to a web page. JavaScript includes a wide variety of built-in functions, which you will learn about throughout this book.

A statement that uses a function, as in the preceding example, is referred to as a function call. Functions take parameters the expression inside the parentheses to tell them what to do.

Additionally, a function can return a value to a waiting variable. For exam- ple, the following function call prompts the user for a response and stores it in the text variable: This is useful for two main reasons: First, you can separate logical portions of your script to make it easier to understand.

Second, and more importantly, you can use the function several times or with differ- ent data to avoid repeating script statements. For example, the following statement creates a variable called fred and assigns it the value For example, did the user enter a valid email address? Testing the Script 63 JavaScript supports conditional statements, which enable you to answer questions like this. A typical conditional uses the if statement, as in this example: You will use conditional statements like this in most of your scripts.

For example, these statements display the same alert 10 times, greatly annoying the user: This is the sort of thing computers are supposed to be good at: You will use loops in many of your scripts, in much more useful ways than this example. Loops are covered in detail in Chapter 8. You can also use scripts as event handlers.

Although this might sound like a complex program- ming term, it actually means exactly what it says: Event handlers are scripts that handle events. In real life, an event is something that happens to you. For example, the things you write on your calendar are events: Creating Simple Scripts in JavaScript Whether events are scheduled or unscheduled, you probably have normal ways of handling them. Event handlers in JavaScript are similar: They tell the browser what to do when a certain event occurs.

Many JavaScript events such as mouse clicks are caused by the user. Each event handler is associated with a particular browser object, and you can spec- ify the event handler in the tag that defines the object. For example, images and text links have an event, onMouseOver, that happens when the mouse pointer moves over the object.

Here is a typical HTML image tag with an event handler: This is an ideal use for functions because function names are short and to the point and can refer to a whole series of statements.

Which Script Runs First? You can actually have several scripts within a web document: With all of these scripts, you might wonder how the browser knows which to execute first.

Fortunately, this is done in a logical fashion: JavaScript Syntax Rules If there is more than one script in the body, they are executed in order. Event handlers are executed when their events happen.

For example, the onLoad event handler is executed when the body of a web page loads. JavaScript Syntax Rules JavaScript is a simple language, but you do need to be careful to use its syntax—the rules that define how you use the language—correctly. The rest of this book covers many aspects of JavaScript syntax, but there are a few basic rules you should under- stand to avoid errors. Case Sensitivity Almost everything in JavaScript is case sensitive: Here are a few general rules: JavaScript keywords, such as for and if, are always lowercase.

Built-in objects such as Math and Date are capitalized. DOM object names are usually lowercase, but their methods are often a com- bination of capitals and lowercase. When in doubt, follow the exact case used in this book or another JavaScript refer- ence. If you use the wrong case, the browser will usually display an error message.

Variable, Object, and Function Names When you define your own variables, objects, or functions, you can choose their names.

Names must begin with a letter or underscore. You can choose whether to use capitals or lowercase in your variable names, but remember that JavaScript is case sensitive: Be sure to use the same name each time you refer to a variable. These include the words that make up the JavaScript language, such as if and for, DOM object names such as window and document, and built-in object names such as Math and Date. Spacing Blank space known as whitespace by programmers is ignored by JavaScript.

You can include spaces and tabs within a line, or blank lines, without causing an error. Blank space often makes the script more readable. Using Comments JavaScript comments enable you to include documentation within your script. This will be useful if someone else tries to understand the script, or even if you try to understand it after a long break.

To include comments in a JavaScript program, begin a line with two slashes, as in this example: You can also begin a comment with two slashes in the middle of a line, which is useful for documenting a script. In this case, everything on the line after the slashes is treated as a comment and ignored by the browser.

These comments can extend across more than one line, as the following example demonstrates: Use comments liberally—These make your code easier for others to under- stand, and also easier for you to understand when you edit them later. They are also useful for marking the major divisions of a script.

Maling Ebook

Use a semicolon at the end of each statement, and only use one statement per line—This will make your scripts easier to debug. Use separate JavaScript files whenever possible—This separates JavaScript from HTML and makes debugging easier, and also encourages you to write modular scripts that can be reused. Avoid them unless absolutely necessary, and always test your code in more than one browser. Whenever possi- ble, users without JavaScript should be able to use your site, although it may not be quite as attractive or convenient.

This strategy is known as progressive enhancement. An Event! In more complex scripts, you will usually define your own function to act as an event handler. Summary 69 Summary During this chapter, you wrote a simple JavaScript program and tested it using a browser.

You learned about the tools you need to work with JavaScript—basically, an editor and a browser. You also learned how to modify and test scripts, and what happens when a JavaScript program runs into an error, and you learned how to use scripts in separate JavaScript files.

You learned how to use JavaScript comments to make your script easier to read, and looked at a simple example of an event handler. Understanding Objects. Working with Web Documents. Accessing Browser History. Understanding Objects JavaScript supports objects. Like variables, objects can store data—but they can store two or more pieces of data at once.

The items of data stored in an object are called the properties of the object. For example, you could use objects to store information about people such as in an address book. The proper- ties of each person object might include a name, an address, and a telephone number. JavaScript uses periods to separate object names and property names. For example, for a person object called Bob, the properties might include Bob.

In JavaScript terminology, the statement Bob. By the The document. You will learn more about this object later in this chapter. For now, you just need to know the basics. JavaScript sup- ports three kinds of objects: Built-in objects are built in to the JavaScript language. For example, the alert function you used earlier in this chapter is actually a method of the window object.

Custom objects are objects you create yourself. Your script can load a new page into the brows- er, work with parts of the browser window and document, open new windows, and even modify text within the page dynamically. These objects are organized into a tree-like structure, and represent all of the content and components of a web document.

The objects in the DOM have properties—variables that describe the web page or doc- ument, and methods—functions that enable you to work with parts of the web page.

When you refer to an object, you use the parent object name followed by the child object name or names, separated by periods. For example, JavaScript stores objects to represent images in a document as children of the document object.


The following refers to the image9 object, a child of the document object, which is a child of the window object: Figure 5. However, there was never a true standard. Working with the Document Object Model DOM Internet Explorer included many of the same objects, there was no guarantee that the same objects would work the same way in both browsers, let alone in less com- mon browsers.

Since the release of Netscape 3. With more recent browser releases, a much more advanced DOM is supported. This is a standard that defines not only basic objects, but an entire set of objects that encompass all parts of an HTML document.

A level 2 DOM standard has also been released, and level 3 is under development. Fortunately, starting with Internet Explorer 5 and Netscape 6, both support the W3C DOM, so you can support both browsers with simple, standards-compliant code.

The basic object hierarchy described in this chapter is informally referred to as DOM level 0, and the objects are included in the DOM level 1 standard. Working with Web Documents The document object represents a web document, or page. Because the window object always represents the current window the one containing the script , you can use window.

You can also simply refer to document, which automatically refers to the current window. The examples in earlier chapters only used a single window and docu- ment, so it was unnecessary to use window. Working with Web Documents 75 If multiple windows or frames are in use, there might be several window objects, each with its own document object. To use one of these document objects, you use the name of the window and the name of the document. In the following sections, you will look at some of the properties and methods of the document object that will be useful in your scripting.

Getting Information About the Document Several properties of the document object include information about the current doc- ument in general: This is a simple text field.

If you need to send the user to a different location, use the window. This date is sent from the server along with the page. As an example of a document property, Listing 5. You could also use the script to always print the current date instead of the last modified date, but that would be cheating. By the You might find that the document. The date is received from the web server, and some servers do not maintain modification dates correctly.

Writing Text in a Document The simplest document object methods are also the ones you will use most often. This statement is used whenever you need to include output in a web page. An alternative statement, document. This is handy when you want your text to be the last thing on the line. Watch Bear in mind that the newline character is displayed as a space by the browser, Out!

You can use these methods only within the body of the web page, so they will be executed when the page loads. You can write new content for a document, however, as the next section explains. You can also use it in a function, provided you include a call to the function within the body of the document.

Using Links and Anchors Another child of the document object is the link object. Actually, there can be multi- ple link objects in a document. Each one includes information about a link to another location or an anchor. Did you You define them with a tag like this: You can then link to Know? You can access link objects with the links array.

Each member of the array is one of the link objects in the current page. A property of the array, document. Each link object or member of the links array has a list of properties defining the URL. The href property contains the entire URL, and other properties define portions of it. These are the same properties as the location object, defined later in this chapter. You can refer to a property by indicating the link number and property name.

For example, the following statement assigns the entire URL of the first link to the vari- able link1: Each anchor object rep- resents an anchor in the current document—a particular location that can be jumped to directly. Like links, you can access anchors with an array: Each element of this array is an anchor object. Accessing Browser History The history object is another child property of the window object. This object holds information about the URLs that have been visited before and after the cur- rent one, and it includes methods to go to previous or next locations.

The history object has one property you can access: The history object has current, previous, and next properties that store URLs By the of documents in the history list.

To use this method, specify a positive or negative number in parentheses. For example, history. This is equivalent to clicking the Forward button. Working with the location Object A third child of the window object is the location object. This object stores informa- tion about the current URL stored in the window. For example, the following state- ment loads a URL into the current window: You can also access portions of the URL with various properties of the location object.

To explain these properties, consider the following URL: Queries are used mostly by CGI scripts. Working with the location Object 79 The link object, introduced earlier this chapter, also includes this list of properties for accessing portions of the URL.

Although the location. URL property. Always use location. The location object has two methods: This is useful for splash screens or temporary pages that it would be useless to return to. You will now create a script that displays Back and Forward buttons and use these methods to navigate the browser.

The onClick event handler uses the history. The code for the Forward button is similar: Listing 5. After you load this document into a browser, visit other URLs and make sure the Back and Forward buttons work. Using Variables.

Understanding Expressions and Operators. Data Types in JavaScript. Converting Between Data Types. Using String Objects. Working with Substrings. Using Numeric Arrays. Using String Arrays. You probably can also figure out how to use a few more without any help. We will now look at some of the details.

Using Variables, Strings, and Arrays Choosing Variable Names Variables are named containers that can store data for example, a number, a text string, or an object. As you learned earlier in this book, each variable has a name. There are specific rules you must follow when choosing a variable name: Variable names can include letters of the alphabet, both upper- and lower- case. Variable names cannot include spaces or any other punctuation characters.

The first character of the variable name must be either a letter or an underscore. Variable names are case sensitive—totalnum, Totalnum, and TotalNum are separate variable names.

There is no official limit on the length of variable names, but they must fit within one line. Using these rules, the following are examples of valid variable names: Do yourself a favor: Use longer, friendly names whenever possible. Using Local and Global Variables Some computer languages require you to declare a variable before you use it.

JavaScript includes the var keyword, which can be used to declare a variable. You can omit var in many cases; the variable is still declared the first time you assign a value to it. To understand where to declare a variable, you will need to understand the concept of scope.

There are two types of variables: Global variables have the entire script and other scripts in the same HTML doc- ument as their scope. They can be used anywhere, even within functions. Using Variables Local variables have a single function as their scope. They can be used only within the function they are created in. To create a global variable, you declare it in the main script, outside any functions. You can use the var keyword to declare the variable, as in this example: If this statement is used outside functions, it creates a global variable.

The var key- word is optional in this case, so this statement is equivalent to the previous one: Way A local variable belongs to a particular function. Any variable you declare with the var keyword in a function is a local variable. To create a local variable within a function, you must use the var keyword.

This forces JavaScript to create a local variable, even if there is a global variable with the same name. You should now understand the difference between local and global variables.

Assigning Values to Variables You can use the equal sign to assign a value to a variable. For example, this state- ment assigns the value 40 to the variable lines: You have used this syntax earlier to add one to a variable: Using Variables, Strings, and Arrays Because incrementing or decrementing variables is quite common, JavaScript includes two types of shorthand for this syntax. This statement adds one to the value of lines: However, these are not identical. The difference is when the increment or decrement happens: If the operator is after the variable name, the increment or decrement hap- pens after the current expression is evaluated.

If the operator is before the variable name, the increment or decrement hap- pens before the current expression is evaluated. This difference is only an issue when you use the variable in an expression and increment or decrement it in the same statement. As an example, suppose you have assigned the lines variable the value The following two statements have differ- ent effects: The second statement first increments lines to 41, then displays an alert with the value By the These operators are strictly for your convenience.

Understanding Expressions and Operators 85 Understanding Expressions and Operators An expression is a combination of variables and values that the JavaScript inter- preter can evaluate to a single value. Along with variables and constant values, you can also use calls to functions that Did you return results within an expression.

Table 6. TABLE 6. For example, consider this statement: Using Variables, Strings, and Arrays If you try to calculate this result, there are two ways to do it. JavaScript solves this dilemma by following the precedence rules: However, because JavaScript gives division a higher precedence than addition, it will divide the d variable by 4 before adding the other numbers, producing an incorrect result.

You can control precedence by using parentheses. Data Types in JavaScript In some computer languages, you have to specify the type of data a variable will store: However, you should know the types of data JavaScript can deal with. Numbers, such as 3, 25, or 1. JavaScript supports both integers and floating-point numbers. Boolean, or logical values. These can have one of two values: These are useful for indicating whether a certain condition is true. These consist of one or more characters of text.

The null value, represented by the keyword null. This is the value of an unde- fined variable. For example, the statement document. For example, suppose you declared a variable by assigning it a value: This is a numeric variable. Now suppose you changed the value of total: Although this feature of JavaScript is convenient and powerful, it can also make it By the easy to make a mistake.

Because the doc- ument. This works equally well with floating-point and Boolean values. For example, the following statement will work fine if the value of total is In some situations, you might end up with a string containing a number, and need to convert it to a regular numeric variable.

JavaScript includes two functions for this purpose: Both of these functions will read a number from the beginning of the string and return a numeric version.

The nonnumeric portion of the string is ignored. By the These functions look for a number of the appropriate type at the beginning of the Way string. If a valid number is not found, the function will return the special value NaN, meaning not a number.

Strings store a group of text characters, and are named similarly to other variables. As a simple example, this statement assigns the string This is a test to a string vari- able called test: There are two ways to create a new String object. The following two statements create the same string: This tells the browser to create a new String object containing the text This is a test, and assigns it to the variable test.

Although you can create a string using object-oriented syntax, the standard By the JavaScript syntax is simpler, and there is no difference in the strings created by Way these two methods.

Assigning a Value You can assign a value to a string in the same way as any other variable. Both of the examples in the previous section assigned an initial value to the string.

You can also assign a value after the string has already been created. For example, the fol- lowing statement replaces the contents of the test variable with a new string: Listing 6. For example, this statement adds a period to the current contents of the string sentence: The browser knows By the whether to use addition or concatenation based on the types of data you use with Way the plus sign.

If you use it between a number and a string, the number is convert- ed to a string and concatenated. You can do this with the length property of String objects, which you can use with any string.

For example, test. Here is an exam- ple of this property: The sec- ond statement displays the length of the string—in this case, 15 characters. Remember that although test refers to a string variable, the value of By the test. For example, the following statement displays the value of the test string variable in lowercase: The toUpperCase and toLowerCase methods do not take any parameters, but you still need to use the parentheses.

JavaScript also enables you to work with substrings, or portions of a string. You can use the substring method to retrieve a portion of a string, or the charAt method to get a single character. These are explained in the following sections. Using Part of a String The substring method returns a string consisting of a portion of the original string between two index values, which you must specify in parentheses.

For example, the following statement displays the fourth through sixth characters of the text string: There are three things you need to understand about the index parameters: Indexing starts with 0 for the first character of the string, so the fourth charac- ter is actually index 3. The second index is noninclusive.

A second index of 6 includes up to index 5 the sixth character. Working with Substrings You can specify the two indexes in either order. The smaller one will be assumed to be the first index. In the previous example, 6,3 would have pro- duced the same result. Of course, there is rarely a reason to use the reverse order. As another example, suppose you defined a string called alpha to hold the alphabet: This is true whenever the two index values are the same.

Getting a Single Character The charAt method is a simple way to grab a single character from a string. The indexes begin at 0 for the first character. Here are a few examples using the alpha string: Using Variables, Strings, and Arrays Finding a Substring Another use for substrings is to find a string within another string. One way to do this is with the indexOf method. To use this method, add indexOf to the string you want to search, and specify the string to search for in the parentheses.

Way Make sure you type it exactly as shown here when you use it in scripts. The value returned in the loc variable is an index into the string, similar to the first index in the substring method. The first character of the string is index 0. You can specify an optional second parameter to indicate the index value to begin the search.

For example, this statement searches for the word fish in the temp string, starting with the 20th character: After finding the first occurrence, you search starting with that location for the second one, and so on. A second method, lastIndexOf , works the same way, but finds the last occurrence of the string. It searches the string backwards, starting with the last character. For example, this statement finds the last occurrence of Fred in the names string: In this case, the string will be searched backward starting at that location.

Using Numeric Arrays An array is a numbered group of data items that you can treat as a single unit. For example, you might use an array called scores to store several scores for a game. Arrays can contain strings, numbers, objects, or other types of data. Each item in an array is called an element of the array. Using Numeric Arrays 95 Creating a Numeric Array Unlike most other types of JavaScript variables, you typically need to declare an array before you use it.

The following example creates an array with four elements: Indexes begin with 0, so the elements of the array in this example would be numbered 0 to 3. These state- ments assign values to the four elements of the array: This statement creates the same scores array in a single line: The following statement is an alternative way to create the scores array: Understanding Array Length Like strings, arrays have a length property. This tells you the number of elements in the array.

For example, these statements would print the number Using Variables, Strings, and Arrays You can declare an array without a specific length, and change the length later by assigning values to elements or changing the length property.

For example, these statements create a new array and assign values to two of its elements: Accessing Array Elements You can read the contents of an array using the same notation you used when assigning values.

For example, the following statements would display the values of the first three elements of the scores array: This is an ideal job for loops, which enable you to perform the same statements several times with different values. JavaScript also allows you to use string arrays, or arrays of strings.

This is a powerful feature that enables you to work with a large number of strings at the same time.Kotlin will overtake Java for Android app development.

Click here to view code image if this condition is true then do this. Can I create a multidimensional array in JavaScript? You just kind of have to do and fail really.

Total Tayangan Halaman

On submitting the form by clicking the Send button, we are taken to http: Yeah, that's the rank of 'Android Developer in 7 days Step by St' amongst all Android Development tutorials recommended by the community. To calculate the remainder from a division. Introducing HTTP. To optimize the presentation of these elements, view the eBook in single-column, landscape mode and adjust the font size to the smallest setting.

JavaScript is not one of these.

ADELINA from Fort Walton Beach
Browse my other posts. I have always been a very creative person and find it relaxing to indulge in tag. I fancy reading books dreamily .