Big collection of basic javascript knowledge (2) recommended collections

Source: Internet
Author: User

For more information, see the attachment example.


1. cookie functions:
Copy codeThe Code is as follows:
/**
* Cookie operation tool.
* Usage: Save value: CookieTool ('name', '1', {expires: 7}) // indicates that a cookie value is saved as 1 and the key value is name, 7 days later
* Value: CookieTool ('name') // return 1
* @ Param {} name
* @ Param {} value
* @ Param {} options
* @ Return {}
*/
CookieTool = function (name, value, options ){
If (typeof value! = 'Undefined '){
Options = options | {};
If (value = null ){
Value = '';
Options. expires =-1;
}
Var expires = '';
If (options. expires & (typeof options. expires = 'number' | options. expires. toUTCString )){
Var date;
If (typeof options. expires = 'number '){
Date = new Date ();
Date. setTime (date. getTime () + (options. expires * 24x60*60*1000 ));
} Else {
Date = options. expires;
}
Expires = '; expires =' + date. toUTCString ();
}
Var path = options. path? '; Path =' + (options. path ):'';
Var domain = options. domain? '; Domain =' + (options. domain ):'';
Var secure = options. secure? '; Secure ':'';
Document. cookie = [name, '=', encodeURIComponent (value), expires, path, domain, secure]. join ('');
} Else {
Var cookieValue = null;
If (document. cookie & document. cookie! = ''){
Var cookies = document. cookie. split (';');
For (var I = 0; I <cookies. length; I ++ ){
Var cookie = trim (cookies [I]);
If (cookie. substring (0, name. length + 1) = (name + '= ')){
CookieValue = decodeURIComponent (cookie. substring (name. length + 1 ));
Break;
}
}
}
Return cookieValue;
}
};

2. About a js function that allows you to view js objects, the cool method is as follows:
Copy codeThe Code is as follows:
/**
* Used to view the attributes of an object
*/
Function debugObjectInfo (obj ){
TraceObject (obj );

Function traceObject (obj ){
Var str = '';
If (obj. tagName & obj. name & obj. id)
Str = "<table border = '1' width = '000000'> <tr> <td colspan = '2' bgcolor = '# ffff99'> traceObject tag: <"+ obj. tagName + "> name = \" "+ obj. name + "\" id = \ "" + obj. id + "\" </td> </tr> ";
Else {
Str = "<table border = '1' width = '000000'> ";
}
Var key = [];
For (var I in obj ){
Key. push (I );
}
Key. sort ();
For (var I = 0; I <key. length; I ++ ){
Var v = new String (obj [key [I]). replace (/</g, "<"). replace (/>/g, "> ");
Str + = "<tr> <td valign = 'top'>" + key [I] + "</td> <td>" + v + "</td> </tr> ";
}
Str = str + "</table> ";
WriteMsg (str );
}
Function trace (v ){
Var str = "<table border = '1' width = '000000'> <tr> <td bgcolor = '# ffff99'> ";
Str + = String (v). replace (/</g, "<"). replace (/>/g, "> ");
Str + = "</td> </tr> </table> ";
WriteMsg (str );
}
Function writeMsg (s ){
TraceWin = window. open ("", "traceWindow", "height = 600, width = 800, scrollbars = yes ");
TraceWin.doc ument. write (s );
}
}

3. Regular Expression:

G indicates global match.
M indicates that multiple rows can be matched.
I indicates case-insensitive matching.
^ Match the start position of the input string
$ Match the end position of the input string
* Match the previous subexpression zero or multiple times. equivalent to {0 ,}
+ Match the previous subexpression once or multiple times. equivalent to {1 ,}
? Matches the previous subexpression zero or one time. It is equivalent to [}. When this character follows any other delimiter (*, + ,?, The matching mode after {n}, {n ,}, {n, m}) is not greedy. The non-Greedy mode matches as few searched strings as possible, while the default greedy mode matches as many searched strings as possible. For example, for strings "oooo", 'O ++? 'Will match a single "o", and 'O +' will match all 'O '.

\ D matches a numeric character. It is equivalent to [0-9]
\ D matches a non-digit character. It is equivalent to [^ 0-9]
\ W, equivalent to "[A-Za-z0-9 _]"
\ W matches any non-word character, equivalent to "[^ A-Za-z0-9]"
\ S matches any blank characters, including space tabs, and so on. It is equivalent to [\ f \ n \ r \ t \ v]
\ S matches any non-blank characters. It is equivalent to [^ \ f \ r \ n \ t \ v]
\ B matches a word boundary, that is, the position between a word and a space.
\ B matches non-word boundaries.

Common js methods for regular expressions:
Copy codeThe Code is as follows:
/**
* Search for substrings that meet the requirements in the source string.
* @ Return {}
*/
Function MatchDemo (){
Var r, re; // declare the variable.
Var s = "The rain in Spain falls mainly in the plain ";
Re = new RegExp ("ain", "g"); // create a regular expression object.
R = s. match (re); // search for matching in string s.
Return (r );
}

/**
* Returns all strings and positions that match the regular expression in the source string.
*/
Function RegExpTest (){
Var ver = Number (ScriptEngineMajorVersion () + "."
+ ScriptEngineMinorVersion ())
Var ans = '';
If (ver> = 5.5) {// test the JScript version.
Var src = "The rain in Spain falls mainly in the plain .";
Var re =/\ w +/g; // create the regular expression mode.
Var arr;
While (arr = re.exe c (src ))! = Null)
Ans + = arr. index + "-" + arr. lastIndex + arr + "\ t ";
} Else {
Ans = "Please use the updated version of JScript ";
}
Return ans;
}

/**
* Check the regular expression of the source string to see if it complies with the regular expression.
*/
Function TestDemo (){
Var s1;
Var source = "abcdefg ";
Var regex =/\ w +/g; // create the regular expression mode.
If (regex. test (source ))
S1 = "contains ";
Else
S1 = "does not contain ";
Return ("'" + source + "'" + s1 + "'" + regex. source + "'");
}

/**
* Find the regular expression string in the source string.
* @ Return {}
*/
Function SearchDemo (){
Var r, re;
Var s = "The rain in Spain falls mainly in the plain .";
Re =/falls/I;
R = s. search (re );
Return (r );
}

4. It is worth learning and a good method to use. call ():
Call ([thisObj [, arg1 [, arg2 [, [,. argN])
Parameters
ThisObj
Optional. Will be used as the object of the current object.
Arg1, arg2, and argN
Optional. The method parameter sequence will be passed.
Description
The call method can be used to call a method instead of another object. The call method can change the object context of a function from the initial context to the new object specified by thisObj.

Simple Example:
Copy codeThe Code is as follows:
Function add (a, B)
{
Alert (a + B );
}
Function sub (a, B)
{
Alert (a-B );
}

Add. call (sub, 3, 1 );
// In this example, add is used to replace sub, add. call (sub, 3, 1) = add (3, 1), so the running result is: alert (4 );

A slightly complex example:
Copy codeThe Code is as follows:
Function Class1 ()
{
This. name = "class1 ";

This. showNam = function ()
{
Alert (this. name );
}
}

Function Class2 ()
{
This. name = "class2 ";
}

Var c1 = new Class1 ();
Var c2 = new Class2 ();

C1.showNam. call (c2 );
// Call means to put the c1 Method on c2 for execution. Originally, c2 does not have the showNam () method. Now it is to put the showNam () method of c1 to c2 for execution, so this. the name should be class2, And the execution result is: alert ("class2 ");

Examples of Multi-inheritance:
Copy codeThe Code is as follows:
Function Class10 ()
{
This. showSub = function (a, B)
{
Alert (a-B );
}
}

Function Class11 ()
{
This. showAdd = function (a, B)
{
Alert (a + B );
}
}


Function Class2 ()
{
Class10.call (this );
Class11.call (this );
}

5. apply function:
The Function. apply (obj, args) method can receive two parameters.
Obj: this object will replace this object in the Function class.
Args: This is an array and it will be passed as a parameter to Function (args --> arguments)
Implement the effect of inheritance similar to call:
Copy codeThe Code is as follows:
Function Person (name, age) {// defines a class, human
This. name = name; // name
This. age = age; // age
This. sayhello = function () {alert ("hello ")};
}
Function Print () {// display class attributes
This. funcName = "Print ";
This. show = function (){
Var msg = [];
For (var key in this ){
If (typeof (this [key])! = "Function "){
Msg. push ([key, ":", this [key]. join (""));
}
}
Alert (msg. join (""));
};
}
Function Student (name, age, grade, school) {// Student Class
Person. apply (this, arguments );
Print. apply (this, arguments );
This. grade = grade; // grade
This. school = school; // school
}
Var p1 = new Person ("jake", 10 );
P1.sayhello ();
Var s1 = new Student ("tom", "Tsinghua Elementary School ");
S1.show ();
S1.sayhello ();
Alert (s1.funcName );

Using apply to optimize the functions of array parameters is a cool method:
Copy codeThe Code is as follows:
Math. max can be followed by any parameter and returns the maximum value among all parameters.

For example
Alert (Math. max (5, 8) // 8
Alert (Math. max (,) // 9

However, in many cases, we need to find the largest element in the array.
Var arr = [5, 7, 9, 1]
Alert (Math. max (arr) // This is not acceptable. Be sure to write it like this

Function getMax (arr ){
Var arrLen = arr. length;
For (var I = 0, ret = arr [0]; I <arrLen; I ++ ){
Ret = Math. max (ret, arr [I]);
}
Return ret;
}

Use apply to read the code:
Function getMax2 (arr ){
Return Math. max. apply (null, arr );
}

The following is another example to merge two Arrays:
Copy codeThe Code is as follows:
Another example is the array push method.
Var arr1 = [1, 3, 4];
Var arr2 = [3, 4, 5];
If we want to expand arr2, append it to arr1 one by one, and finally let arr1 = [1, 3, 4, 5]
Arr1.push (arr2) obviously does not work. In this case, [, 4, [, 5] is obtained.

We can only use one loop to push one by one (of course, arr1.concat (arr2) can also be used, but the concat method does not change the arr1 itself)
Var arrLen = arr2.length
For (var I = 0; I <arrLen; I ++ ){
Arr1.push (arr2 [I]);
}

If you use apply:
Copy codeThe Code is as follows:
Array. prototype. push. apply (arr1, arr2)

Package download http://xiazai.jb51.net/201101/yuanma/MyHtml.rar

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.