|Language:||English, French, German|
|ePub File Size:||22.45 MB|
|PDF File Size:||16.66 MB|
|Distribution:||Free* [*Sign up for free]|
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.
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.
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.
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.
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.
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?
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?
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Variable, Object, and Function Names When you define your own variables, objects, or functions, you can choose their names.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.