1. Trang chủ
  2. » Công Nghệ Thông Tin

JavaScript Bible, Gold Edition part 116 pptx

10 171 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề JavaScript Core Language Reference
Thể loại Tài liệu tham khảo
Định dạng
Số trang 10
Dung lượng 192,03 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Therefore, if an array named CDCollectionhas been created and a proto-type method showCoverImagehas been attached to the array, the call to invoke the method for a tenth listing in the a

Trang 1

When you need to call upon that function (which has essentially become a new temporary method for the Arrayobject), invoke it as you would any object method Therefore, if an array named CDCollectionhas been created and a proto-type method showCoverImage()has been attached to the array, the call to invoke the method for a tenth listing in the array is

CDCollection.showCoverImage(9)

where the parameter of the function uses the index value to perhaps retrieve an image whose URL is a property of an object assigned to the 10th item of the array

Array Object Methods

After you have information stored in an array, JavaScript provides several meth-ods to help you manage that data These methmeth-ods, all of which belong to array objects you create, have evolved over time, so observe carefully which browser versions a desired method works with

array.concat(array2)

Returns: array Object.

NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5

The array.concat()method allows you to join two array objects into a new, third array object The action of concatenating the arrays does not alter the con-tents or behavior of the two original arrays To join the arrays, you refer to the first array object to the left of the period before the method; a reference to the second array is the parameter to the method For example:

var array1 = new Array(1,2,3) var array2 = new Array(“a”,”b”,”c”) var array3 = array1.concat(array2) // result: array with values 1,2,3,”a”,”b”,”c”

If an array element is a string or number value (not a string or number object), the values are copied from the original arrays into the new one All connection with the original arrays ceases for those items But if an original array element is a refer-ence to an object of any kind, JavaScript copies a referrefer-ence from the original array’s entry into the new array So if you make a change to either array’s entry, the change occurs to the object, and both array entries reflect the change to the object Example (with Figure 37-1 and Listing 37-6) on the CD-ROM

Related Items:array.join()method

On the

CD-ROM

array.concat()

Trang 2

Returns: String of entries from the array delimited by the separatorString value.

NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5

You cannot view data in an array when it’s in that form Nor can you put an array

into a form element for transmittal to a server CGI program To make the transition

from discrete array elements to string, the array.join()method handles what

would otherwise be a nasty string manipulation exercise

The sole parameter for this method is a string of one or more characters that

you want to act as a delimiter between entries For example, if you want commas

between array items in their text version, the statement is

var arrayText = myArray.join(“,”)

Invoking this method does not change the original array in any way Therefore,

you need to assign the results of this method to another variable or a value

prop-erty of a form element

Example (with Listing 37-7) on the CD-ROM

Related Items:string.split()method

array.pop()

array.push(valueOrObject)

array.shift()

array.unshift(valueOrObject)

Returns: One array entry value.

NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5

The notion of a stack is well known to experienced programmers, especially

those who know about the inner workings of assembly language at the CPU level

Even if you’ve never programmed a stack before, you have encountered the

con-cept in real life many times The classic analogy is the spring-loaded pile of

cafete-ria trays If the pile were created one tray at a time, each tray would be pushed into

the stack of trays When a customer comes along, the topmost tray (the last one to

be pushed onto the stack) gets popped off The last one to be put on the stack is

the first one to be taken off

On the

CD-ROM

array.pop()

Trang 3

JavaScript in NN4+ and IE5.5 lets you turn an array into one of these spring-loaded stacks But instead of placing trays on the pile, you can place any kind of data at either end of the stack, depending on which method you use to do the stacking Similarly, you can extract an item from either end

Perhaps the most familiar terminology for this is push and pop When you

push()a value onto an array, the value is appended as the last entry in the array When you issue the array.pop()method, the last item in the array is removed from the stack and is returned, and the array shrinks in length by one In the follow-ing sequence of statements, watch what happens to the value of the array used as a stack:

var source = new Array(“Homer”,”Marge”,”Bart”,”Lisa”,”Maggie”) var stack = new Array()

// stack = <empty>

stack.push(source[0]) // stack = “Homer”

stack.push(source[2]) // stack = “Homer”,”Bart”

var Simpson1 = stack.pop() // stack = “Homer” ; Simpson1 = “Bart”

var Simpson2 = stack.pop() // stack = <empty> ; Simpson2 = “Homer”

While push()and pop()work at the end of an array, another pair of methods works at the front Their names are not as picturesque as push()and pop() To insert a value at the front of an array, use the array.unshift()method; to grab the first element and remove it from the array, use array.shift() Of course, you are not required to use these methods in matching pairs If you push()a series of values onto the back end of an array, you can shift()them off from the front end without complaint It all depends on how you need to process the data

Related Items:array.concat(), array.slice()method

array.reverse()

Returns: Array of entries in the opposite order of the original.

NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5

Occasionally, you may find it more convenient to work with an array of data in reverse order Although you can concoct repeat loops to count backward through index values, a CGI program on the server may prefer the data in a sequence oppo-site to the way it was most convenient for you to script it

You can have JavaScript switch the contents of an array for you: Whatever ele-ment was last in the array becomes the 0 index item in the array Bear in mind that

if you do this, you’re restructuring the original array, not copying it, even though the method also returns a copy of the reversed version A reload of the document restores the order as written in the HTML document

array.reverse()

Trang 4

Example (with Listing 37-8) on the CD-ROM

Related Items:array.sort()method

array.slice(startIndex [, endIndex])

Returns: Array.

NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5

Behaving as its like-named string method, array.slice()lets you extract a

con-tiguous series of items from an array The extracted segment becomes an entirely

new array object Values and objects from the original array have the same kind of

behavior as arrays created with the array.concat()method

One parameter is required — the starting index point for the extraction If you

don’t specify a second parameter, the extraction goes all the way to the end of the

array; otherwise the extraction goes to, but does not include, the index value

sup-plied as the second parameter For example, extracting Earth’s neighbors from an

array of planet names looks as the following

var solarSys = new Array(“Mercury”,”Venus”,”Earth”,”Mars”,”Jupiter”,”Saturn”,

“Uranus”,”Neptune”,”Pluto”) var nearby = solarSys.slice(1,4)

// result: new array of “Venus”, “Earth”, “Mars”

Related Items:array.splice(), string.slice()methods

array.sort([compareFunction])

Returns: Array of entries in the order as determined by the compareFunction

algorithm

NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5

JavaScript array sorting is both powerful and a bit complex to script if you

haven’t had experience with this kind of sorting methodology The purpose,

obvi-ously, is to let your scripts sort entries of an array by almost any kind of criterion

that you can associate with an entry For entries consisting of strings, the criterion

may be their alphabetical order or their length; for numeric entries, the criterion

may be their numerical order

On the

CD-ROM

array.sort()

Trang 5

Look first at the kind of sorting you can do with the array.sort()method by itself (for example, without calling a comparison function) When no parameter is specified, JavaScript takes a snapshot of the contents of the array and converts items to strings From there, it performs a string sort of the values ASCII values of characters govern the sort, which means that numbers are sorted by their string values, not their numeric values This fact has strong implications if your array con-sists of numeric data: The value 201 sorts before 88, because the sorting mecha-nism compares the first characters of the strings (“2” versus “8”) to determine the sort order For simple alphabetical sorting of string values in arrays, the plain

array.sort()method does the trick

Fortunately, additional intelligence is available that you can add to array sorting The key tactic is to define a function that helps the sort()method compare items in the array A comparison function is passed two values from the array (what you don’t see is that the array.sort()method rapidly sends numerous pairs of values from the array to help it sort through all entries) The comparison function lets the sort() method know which of the two items comes before the other, based on the value the function returns Assuming that the function compares two values, aand b, the returned value reveals information to the sort()method, as shown in Table 37-1

Table 37-1 Comparison Function Return Values

Return Value Range Meaning

< 0 Value b should sort later than a

0 The order of a and b should not change

> 0 Value a should sort later than b

Consider the following example:

myArray = new Array(12, 5, 200, 80) function compare(a,b) {

return a - b }

myArray.sort(compare)

The array has four numeric values in it To sort the items in numerical order, you define a comparison function (arbitrarily named compare()), which is called from the sort()method Note that unlike invoking other functions, the parameter of the sort()method uses a reference to the function, which lacks parentheses

When the compare()function is called, JavaScript automatically sends two parameters to the function in rapid succession until each element has been com-pared with the others Every time compare()is called, JavaScript assigns two of the array’s values to the parameter variables (aand b) In the preceding example, the returned value is the difference between aand b If ais larger than b, then a positive value goes back to the sort()method, telling it to sort alater than b(that

is, position aat a higher value index position than b) Therefore, bmay end up at myArray[0], whereas aends up at a higher index-valued location On the other

array.sort()

Trang 6

hand, if ais smaller than b, then the returned negative value tells sort()to put ain

a lower index value spot than b

Evaluations within the comparison function can go to great lengths, as long as

some data connected with array values can be compared For example, instead of

numerical comparisons, as just shown, you can perform string comparisons The

following function sorts alphabetically by the last character of each array string

entry:

function compare(a,b) {

// last character of array strings

var aComp = a.charAt(a.length - 1)

var bComp = b.charAt(b.length - 1)

if (aComp < bComp) {return -1}

if (aComp > bComp) {return 1}

return 0

}

First, this function extracts the final character from each of the two values

passed to it Then, because strings cannot be added or subtracted like numbers,

you compare the ASCII values of the two characters, returning the corresponding

values to the sort()method to let it know how to treat the two values being

checked at that instant

When an array’s entries happen to be objects, you can even sort by properties of

those objects If you bear in mind that the aand bparameters of the sort function

are references to two array entries, then by extension you can refer to properties of

those objects For example, if an array contains objects whose properties define

information about employees, one of the properties of those objects can be the

employee’s age as a string You can then sort the array based on the numeric

equiv-alent of ageproperty of the objects by way of the following comparison function:

function compare(a,b) {

return parseInt(a.age) - parseInt(b.age)

}

Array sorting, unlike sorting routines you may find in other scripting languages,

is not a stable sort Not being stable means that succeeding sort routines on the

same array are not cumulative Also, remember that sorting changes the sort order

of the original array If you don’t want the original array harmed, make a copy of it

before sorting or reload the document to restore an array to its original order

Should an array element be null, the method sorts such elements at the end of

the sorted array starting with Navigator 4 (instead of leaving them in their original

places as in Navigator 3)

Unfortunately, this powerful method does not work in the Macintosh version of

Navigator 3 Starting with Navigator 4, all platforms have the feature

JavaScript array sorting is extremely powerful stuff Array sorting is one reason

why it’s not uncommon to take the time during the loading of a page containing an

IE XML data island to make a JavaScript copy of the data as an array of objects (see

Chapter 57) Converting the XML to JavaScript arrays makes the job of sorting the

data much easier and faster than cobbling together your own sorting routines on

the XML elements

Note

array.sort()

Trang 7

Example (with Listing 37-9) on the CD-ROM

Related Items:array.reverse()method

As I show you in Chapter 38, many regular expression object methods generate arrays as their result (for example, an array of matching values in a string) These special arrays have a custom set of named properties that assist your script in ana-lyzing the findings of the method Beyond that, these regular expression result arrays behave like all others

array.splice(startIndex , deleteCount[, item1[, item2[, itemN]]])

Returns: Array.

NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5

If you need to remove items from the middle of an array, the array.splice()

method (not implemented in IE5/Mac) simplifies a task that would otherwise require assembling a new array from selected items of the original array The first of two required parameters is a zero-based index integer that points to the first item

to be removed from the current array The second parameter is another integer that indicates how many sequential items are to be removed from the array Removing array items affects the length of the array, and those items that are removed are returned by the splice()method as their own array

You can also use the splice()method to replace array items Optional parame-ters beginning with the third let you provide data elements that are to be inserted into the array in place of the items being removed Each added item can be any JavaScript data type, and the number of new items does not have to be equal to the number of items removed In fact, by specifying a second parameter of zero, you can use splice()to insert one or more items into any position of the array

Example on the CD-ROM

Related Items:array.slice()method

On the

CD-ROM

Note

On the

CD-ROM

array.splice()

Trang 8

Returns: String.

NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5

array.toString()

Returns: String.

NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5

The array.toLocaleString()and the older, more compatible

array.toString()are methods to retrieve the contents of an array in string form

Browsers use the toString()method on their own whenever you attempt to

dis-play an array in text boxes, in which case the array items are comma-delimited

The precise string conversion of the toLocaleString()is left up to the specific

browser implementation That IE5.5 and NN6 differ in some details is not surprising,

even in the U.S English versions of operating systems and browsers For example, if

the array contains integer values, IE5.5’s toLocaleString()method returns the

numbers comma-and-space-delimited, formatted with two digits to the right of the

decimal (as if dollars and cents) NN6, on the other hand, returns just the integers,

but these are also comma-and-space-delimited

If you need to convert an array to a string for purposes of passing array data to

other venues (for example, as data in a hidden text box submitted to a server or as

search string data conveyed to another page), use the array.join()method

instead Array.join()gives you more reliable and flexible control over the item

delimiters, and you are assured of the same results regardless of locale

Related Items:array.join()method

array.toString()

Trang 10

The Regular

Expression and

RegExp Objects

Web programmers who have worked in Perl (and other

Web application programming languages) know the

power of regular expressions for processing incoming data

and formatting data for readability in an HTML page or for

accurate storage in a server database Any task that requires

extensive search and replacement of text can greatly benefit

from the flexibility and conciseness of regular expressions

Navigator 4 and Internet Explorer 4 (more fully fleshed out in

IE5.5) bring that power to JavaScript

Most of the benefit of JavaScript regular expressions

accrues to those who script their CGI programs on servers

that support a JavaScript version that contains regular

expressions But that’s not to exclude the client-side from

application of this “language within a language.” If your

scripts perform client-side data validations or any other

extensive text entry parsing, then consider using regular

expressions, rather than cobbling together comparatively

complex JavaScript functions to perform the same tasks

Regular Expressions and Patterns

In several chapters earlier in this book, I describe

expres-sions as any sequence of identifiers, keywords, and/or

opera-tors that evaluate to some value A regular expression follows

that description, but has much more power behind it In

essence, a regular expression uses a sequence of characters

and symbols to define a pattern of text Such a pattern is used

to locate a chunk of text in a string by matching up the

pat-tern against the characters in the string

An experienced JavaScript writer may point out the

avail-ability of the string.indexOf()and string.lastIndexOf()

methods that can instantly reveal whether a string contains a

substring and even where in the string that substring begins

These methods work perfectly well when the match is exact,

38

In This Chapter

What regular expressions are

How to use regular expressions for text search-and-replace How to apply regular expressions to string object methods

Ngày đăng: 06/07/2014, 06:20