javascript guide
相关连接
https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide
http://www.moko.ru/doc/Java_Script/index.html
http://www.w3school.com.cn/htmldom/dom_obj_style.asp
http://www.w3school.com.cn/css/css_reference.asp
https://developer.mozilla.org/en/Gecko_DOM_Reference
https://developer.mozilla.org/en/The_DOM_and_JavaScript
https://developer.mozilla.org/en/DOM/document
https://developer.mozilla.org/en/AJAX
http://jquery-api-zh-cn.googlecode.com/svn/trunk/xml/jqueryapi.xml
http://webteam.tencent.com/css3/
dynamically typed动态性:
var a = "1234";
//then
a = 12345;
//it 's ok
//+加号自动转换为字符串,其他不会
a+"aaaa"= 12345aaaa
a - "5" = 12340
string object
"one line \n another line"
The following table lists the special characters that you can use in JavaScript strings.
Character | Meaning |
---|---|
\b | Backspace |
\f | Form feed |
\n | New line |
\r | Carriage return |
\t | Tab |
\v | Vertical tab |
\' | Apostrophe or single quote |
\" | Double quote |
\\ | Backslash character (\). |
\XXX | The character with the Latin-1 encoding specified by up to three octal digits XXX between 0 and 377. For example, \251 is the octal sequence for the copyright symbol. |
\xXX | The character with the Latin-1 encoding specified by the two hexadecimal digits XX between 00 and FF. For example, \xA9 is the hexadecimal sequence for the copyright symbol. |
\uXXXX | The Unicode character specified by the four hexadecimal digits XXXX . For example, \u00A9 is the Unicode sequence for the copyright symbol. See Unicode escape sequences . |
比较
Operator | Description | Examples returning true |
---|---|---|
Equal (==) | Returns true if the operands are equal. | 3 == var1
3 == '3' |
Not equal (!=) | Returns true if the operands are not equal. | var1 != 4 |
Strict equal (===) | Returns true if the operands are equal and of the same type. | 3 === var1 |
Strict not equal (!==) | Returns true if the operands are not equal and/or not of the same type. | var1 !== "3" |
Greater than (>) | Returns true if the left operand is greater than the right operand. | var2 > var1 |
Greater than or equal (>=) | Returns true if the left operand is greater than or equal to the right operand. | var2 >= var1 |
Less than (<) | Returns true if the left operand is less than the right operand. | var1 < var2 |
Less than or equal (<=) | Returns true if the left operand is less than or equal to the right operand. | var1 <= var2 |
Special Operators
Table of contents
- 1. Special Operators
- 1.1. conditional operator
- 1.2. comma operator
- 1.3. delete
- 1.4. in
- 1.5. instanceof
- 1.6. new
- 1.7. this
- 1.8. typeof
- 1.9. void
Special Operators
JavaScript provides the following special operators:
conditional operator
The conditional operator is the only JavaScript operator that takes three operands. The operator can have one of two values based on a condition. The syntax is:
condition ? val1 : val2
If condition
is true, the operator has the value of val1
. Otherwise it has the value of val2
. You can use the conditional operator anywhere you would use a standard operator.
For example,
status = (age >= 18) ? "adult" : "minor"
This statement assigns the value "adult" to the variable status
if age
is eighteen or more. Otherwise, it assigns the value "minor" to status
.
comma operator
The comma operator (,) simply evaluates both of its operands and returns the value of the second operand. This operator is primarily used inside a for
loop, to allow multiple variables to be updated each time through the loop.
For example, if a
is a 2-dimensional array with 10 elements on a side, the following code uses the comma operator to increment two variables at once. The code prints the values of the diagonal elements in the array:
for (var i=0, j=9; i <= 9; i++, j--) document.writeln("a["+i+"]["+j+"]= " + a[i][j])
delete
The delete operator deletes an object, an object's property, or an element at a specified index in an array. The syntax is:
delete objectName delete objectName.property delete objectName[index] delete property // legal only within a with statement
where objectName
is the name of an object, property
is an existing property, and index
is an integer representing the location of an element in an array.
The fourth form is legal only within a with
statement, to delete a property from an object.
You can use the delete
operator to delete variables declared implicitly but not those declared with the var
statement.
If the delete
operator succeeds, it sets the property or element to undefined
. The delete
operator returns true if the operation is possible; it returns false if the operation is not possible.
x=42 var y= 43 myobj=new Number() myobj.h=4 // create property h delete x // returns true (can delete if declared implicitly) delete y // returns false (cannot delete if declared with var) delete Math.PI // returns false (cannot delete predefined properties) delete myobj.h // returns true (can delete user-defined properties) delete myobj // returns true (can delete if declared implicitly)
Deleting array elements
When you delete an array element, the array length is not affected. For example, if you delete a[3], a[4] is still a[4] and a[3] is undefined.
When the delete
operator removes an array element, that element is no longer in the array. In the following example, trees[3] is removed with delete
.
trees=new Array("redwood","bay","cedar","oak","maple") delete trees[3] if (3 in trees) { // this does not get executed }
If you want an array element to exist but have an undefined value, use the undefined
keyword instead of the delete
operator. In the following example, trees[3]
is assigned the value undefined
, but the array element still exists:
trees=new Array("redwood","bay","cedar","oak","maple") trees[3]=undefined if (3 in trees) { // this gets executed }
in
The in
operator returns true if the specified property is in the specified object. The syntax is:
propNameOrNumber in objectName
where propNameOrNumber
is a string or numeric expression representing a property name or array index, and objectName
is the name of an object.
The following examples show some uses of the in
operator.
// Arrays trees=new Array("redwood","bay","cedar","oak","maple") 0 in trees // returns true 3 in trees // returns true 6 in trees // returns false "bay" in trees // returns false (you must specify the index number, // not the value at that index) "length" in trees // returns true (length is an Array property) // Predefined objects "PI" in Math // returns true myString=new String("coral") "length" in myString // returns true // Custom objects mycar = {make:"Honda",model:"Accord",year:1998} "make" in mycar // returns true "model" in mycar // returns true
instanceof
The instanceof
operator returns true if the specified object is of the specified object type. The syntax is:
objectName instanceof objectType
where objectName
is the name of the object to compare to objectType
, and objectType
is an object type, such as Date
or Array
.
Use instanceof
when you need to confirm the type of an object at runtime. For example, when catching exceptions, you can branch to different exception-handling code depending on the type of exception thrown.
For example, the following code uses instanceof
to determine whether theDay
is a Date
object. Because theDay
is a Date
object, the statements in the if
statement execute.
theDay=new Date(1995, 12, 17) if (theDay instanceof Date) { // statements to execute }
new
You can use the new
operator to create an instance of a user-defined object type or of one of the predefined object types Array, Boolean, Date, Function, Image, Number, Object, Option, RegExp
, or String
. On the server, you can also use it with DbPool, Lock, File,
or SendMail
. Use new
as follows:
objectName = new objectType ( param1 [,param2] ...[,paramN] )
You can also create objects using object initializers, as described in Using Object Initializers .
See the new Operator page in the Core JavaScript Reference for more information.
this
Use the this
keyword to refer to the current object. In general, this
refers to the calling object in a method. Use this
as follows:
this[propertyName]
Example 1.
Suppose a function called validate
validates an object's value
property, given the object and the high and low values:
function validate(obj, lowval, hival) { if ((obj.value < lowval) || (obj.value > hival)) alert("Invalid Value!") }
You could call validate
in each form element's onChange
event handler, using this
to pass it the form element, as in the following example:
<B>Enter a number between 18 and 99:</B> <INPUT TYPE = "text" NAME = "age" SIZE = 3 onChange="validate(this, 18, 99)">
Example 2.
When combined with the form
property, this
can refer to the current object's parent form. In the following example, the form myForm
contains a Text
object and a button. When the user clicks the button, the value of the Text
object is set to the form's name. The button's onClick
event handler uses this.form
to refer to the parent form, myForm
.
<FORM NAME="myForm"> Form name:<INPUT TYPE="text" NAME="text1" VALUE="Beluga"> <P> <INPUT NAME="button1" TYPE="button" VALUE="Show Form Name" onClick="this.form.text1.value=this.form.name"> </FORM>
typeof
The typeof
operator is used in either of the following ways:
1. typeof operand 2. typeof (operand)
The typeof
operator returns a string indicating the type of the unevaluated operand. operand
is the string, variable, keyword, or object for which the type is to be returned. The parentheses are optional.
Suppose you define the following variables:
var myFun = new Function("5+2") var shape="round" var size=1 var today=new Date()
The typeof
operator returns the following results for these variables:
typeof myFun is function typeof shape is string typeof size is number typeof today is object typeof dontExist is undefined
For the keywords true
and null
, the typeof
operator returns the following results:
typeof true is boolean typeof null is object
For a number or string, the typeof
operator returns the following results:
typeof 62 is number typeof 'Hello world' is string
For property values, the typeof
operator returns the type of value the property contains:
typeof document.lastModified is string typeof window.length is number typeof Math.LN2 is number
For methods and functions, the typeof
operator returns results as follows:
typeof blur is function typeof eval is function typeof parseInt is function typeof shape.split is function
For predefined objects, the typeof
operator returns results as follows:
typeof Date is function typeof Function is function typeof Math is function typeof Option is function typeof String is function
void
The void
operator is used in either of the following ways:
1. void (expression) 2. void expression
The void
operator specifies an expression to be evaluated without returning a value. expression
is a JavaScript expression to evaluate. The parentheses surrounding the expression are optional, but it is good style to use them.
You can use the void
operator to specify an expression as a hypertext link. The expression is evaluated but is not loaded in place of the current document.
The following code creates a hypertext link that does nothing when the user clicks it. When the user clicks the link, void(0)
evaluates to undefined, which has no effect in JavaScript.
<A HREF="javascript:void(0)">Click here to do nothing</A>
The following code creates a hypertext link that submits a form when the user clicks it.
<A HREF="javascript:void(document.form.submit())"> Click here to submit</A>
正则表达
<script type="text/javascript"> re = /(\w+)\s(\w+)/; str = "John Smith"; newstr = str.replace(re, "$2, $1"); document.write(newstr); </script>
This prints "Smith, John".
Array Object
JavaScript does not have an explicit array data type. However, you can use the predefined Array
object and its methods to work with arrays in your applications. The Array
object has methods for manipulating arrays in various ways, such as joining, reversing, and sorting them. It has a property for determining the array length and other properties for use with regular expressions.
An array is an ordered set of values that you refer to with a name and an index. For example, you could have an array called emp
that contains employees' names indexed by their employee number. So emp[1]
would be employee number one, emp[2]
employee number two, and so on.
Creating an Array
To create an Array
object:
1. arrayObjectName = new Array(element0, element1, ..., elementN) 2. arrayObjectName = new Array(arrayLength)
arrayObjectName
is either the name of a new object or a property of an existing object. When using Array
properties and methods, arrayObjectName is either the name of an existing Array
object or a property of an existing object.
element0, element1, ..., elementN
is a list of values for the array's elements. When this form is specified, the array is initialized with the specified values as its elements, and the array's length property is set to the number of arguments.
arrayLength
is the initial length of the array. The following code creates an array of five elements:
billingMethod = new Array(5)
Array literals are also Array
objects; for example, the following literal is an Array
object. See Array Literals for details on array literals.
coffees = ["French Roast", "Columbian", "Kona"]
Populating an Array
You can populate an array by assigning values to its elements. For example,
emp[1] = "Casey Jones" emp[2] = "Phil Lesh" emp[3] = "August West"
You can also populate an array when you create it:
myArray = new Array("Hello", myVar, 3.14159)
Referring to Array Elements
You refer to an array's elements by using the element's ordinal number. For example, suppose you define the following array:
myArray = new Array("Wind","Rain","Fire")
You then refer to the first element of the array as myArray[0]
and the second element of the array as myArray[1]
.
The index of the elements begins with zero (0), but the length of array (for example, myArray.length
) reflects the number of elements in the array.
Array Methods
The Array
object has the following methods:
-
concat
joins two arrays and returns a new array.
myArray = new Array("1","2","3") myArray = myArray.concat("a", "b", "c"); // myArray is now ["1", "2", "3", "a", "b", "c"]
-
join(deliminator = ",")
joins all elements of an array into a string.
myArray = new Array("Wind","Rain","Fire") list = myArray.join(" - "); // list is "Wind - Rain - Fire"
-
pop
removes the last element from an array and returns that element.
myArray = new Array("1", "2", "3"); last=myArray.pop(); // MyArray is now ["1", "2"], last = "3"
-
push
adds one or more elements to the end of an array and returns the resulting length of the array.
myArray = new Array("1", "2"); myArray.push("3"); // MyArray is now ["1", "2", "3"]
-
reverse
transposes the elements of an array: the first array element becomes the last and the last becomes the first.
myArray = new Array ("1", "2", "3"); myArray.reverse(); // transposes the array so that myArray = [ "3", "2", "1" ]
-
shift
removes the first element from an array and returns that element
myArray = new Array ("1", "2", "3"); first=myArray.shift(); // MyArray is now ["2", "3"], first is "1"
-
slice (start_index, upto_index)
extracts a section of an array and returns a new array.
myArray = new Array ("a", "b", "c", "d", "e"); myArray = myArray.slice(1,4); //starts at index 1 and extracts all elements until index 4, returning [ "b", "c", "d", "e" ]
-
splice(index, count_to_remove, addelement1, addelement2, ...)
adds and/or removes elements from an array.
myArray = new Array ("1", "2", "3", "4", "5"); myArray.splice(1,3,"a","b","c", "d"); // MyArray is now ["1", "a", "b", "c", "d", "5"] // This code started at index one (or where the "2" was), removed 3 elements there, // and then inserted all consecutive elements in its place.
-
sort
sorts the elements of an array.
myArray = new Array("Wind","Rain","Fire") myArray.sort(); // sorts the array so that myArrray = [ "Fire", "Rain", "Wind" ]
sort
can also take a callback function to determine how array content is sorted. The function compares two values and returns one of three values:
- if a is less than b by the sorting system, return -1 (or any negative number)
- if a is greater than b by the sorting system, return 1 (or any positive number)
- if a and b is considered equivalent, return 0.
For, instance, the following will sort by the last letter of an array:
var sortFn = function(a,b){ if (a[a.length - 1] < b[b.length - 1]) return -1; if (a[a.length - 1] > b[b.length - 1]) return 1; if (a[a.length - 1] == b[b.length - 1]) return 0; } myArray.sort(sortFn); // sorts the array so that myArray = ["Wind","Fire","Rain"]
-
unshift
adds one or more elements to the front of an array and returns the new length of the array.
Two-Dimensional Arrays
The following code creates a two-dimensional array.
a = new Array(4) for (i=0; i < 4; i++) { a[i] = new Array(4) for (j=0; j < 4; j++) { a[i][j] = "["+i+","+j+"]" } }
This example creates an array with the following rows:
Row 0:[0,0][0,1][0,2][0,3] Row 1:[1,0][1,1][1,2][1,3] Row 2:[2,0][2,1][2,2][2,3] Row 3:[3,0][3,1][3,2][3,3]
Arrays and Regular Expressions
When an array is the result of a match between a regular expression and a string, the array returns properties and elements that provide information about the match. An array is the return value of RegExp.exec
, String.match
, and String.split
. For information on using arrays with regular expressions, see Chapter 4, Regular Expressions .
string object method:
Method | Description |
---|---|
anchor | Creates HTML named anchor. |
big , blink , bold , fixed , italics , small , strike , sub , sup | Create HTML formatted string. |
charAt , charCodeAt | Return the character or character code at the specified position in string. |
indexOf , lastIndexOf | Return the position of specified substring in the string or last position of specified substring, respectively. |
link | Creates HTML hyperlink. |
concat | Combines the text of two strings and returns a new string. |
fromCharCode | Constructs a string from the specified sequence of Unicode values. This is a method of the String class, not a String instance. |
split | Splits a String object into an array of strings by separating the string into substrings. |
slice | Extracts a section of an string and returns a new string. |
substring , substr | Return the specified subset of the string, either by specifying the start and end indexes or the start index and a length. |
match , replace , search | Work with regular expressions. |
toLowerCase , toUpperCase | Return the string in all lowercase or all uppercase, respectively. |
Class-based (Java) | Prototype-based (JavaScript) |
---|---|
Class and instance are distinct entities. | All objects are instances. |
Define a class with a class definition; instantiate a class with constructor methods. | Define and create a set of objects with constructor functions. |
Create a single object with the new operator. | Same. |
Construct an object hierarchy by using class definitions to define subclasses of existing classes. | Construct an object hierarchy by assigning an object as the prototype associated with a constructor function. |
Inherit properties by following the class chain. | Inherit properties by following the prototype chain. |
Class definition specifies all properties of all instances of a class. Cannot add properties dynamically at run time. | Constructor function or prototype specifies an initial set of properties. Can add or remove properties dynamically to individual objects or to the entire set of objects. |
element.attachEvent(eventName,eventHandler,useCapture);
element.addEventListener(eventName,eventHandler,useCapture);
//useCapture=true,false
//useCapture为是否使用捕获模式,即从外向内的模式。
获得event的元素:
function imgClick(){
alert(event.srcElement.src);//Mozzilla中使用event.target属性
}
直接调用函数:
var i = function (a,b){
return a+b;
}(1,2);
alert(i);
//这里i输出为3,因为()比=更高优先级
通过prototype,修改、扩充对象的定义,如:
Function.prototype.method1=function(){alert("function");};//扩展Function对象
function func1(a,b,c){return a+b+c};
func1.method1();
隐含参数:arguments
函数Function.apply,Function.call
类似于java的反射中method.invoke(obj,arg);
apply(thisArg,argArray)
call(thisArg,arg1,arg2)
this指针
用function构造类
function class1(){}
var obj = new class1();