A great collection of JavaScript Basics (ii) Recommended collection _ Basic knowledge

Source: Internet
Author: User
Tags inheritance numeric tagname
A detailed look at the attachment example, or write a relatively simple.


1. Functions on Cookies:
Copy Code code as follows:

/**
* Cookie Operation tool.
* Use Method: Save value: Cookietool (' name ', ' 1 ', {expires:7})//= save a cookie value of 1, key value is name, Expiration time 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 * 24 * 60 * 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 one can see JS object js function, very cool method:
Copy Code code as follows:

/**
* Used to view the properties 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= ' 100% ' ><tr><td colspan= ' 2 ' bgcolor= ' #ffff99 ' >traceobject tag: < ' + obj.tagname+ "> name = \" "+obj.name+" \ "id = \" "+obj.id+" \ "</td></tr>";
else{
str= "<table border= ' 1 ' width= ' 100% ' >";
}
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= ' 100% ' ><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.document.write (s);
}
}

3. Regular Expressions:

G represents a global match
M stands for multiple line matches
I represents case-insensitive matching
^ match the start position of the input string
$ matches the end position of the input string
* Match the preceding subexpression 0 or more times. Equivalent to {0,}
+ matches the preceding subexpression one or more times. Equivalent to {1,}
? Matches the preceding subexpression 0 times or once. equivalent to [0,1}, when the character follows any other qualifier (*, +,?, {n}, {n,}, {n,m}), the matching pattern is not greedy. Non-greedy patterns match as few strings as possible, while the default greedy pattern matches as many of the searched strings as possible. For example, for the string "oooo", ' o+? ' will match a single "O", and ' o+ ' will match all ' o '.

\d matches a numeric character. equivalent to [0-9]
\d matches a non-numeric character. 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 white-space character, including a Space-tab-page break, and so on. equivalent to [\f\n\r\t\v]
\s matches any non-white-space character. equivalent to [^\f\r\n\t\v]
\b Matches a word boundary, which refers to the position between the word and the space.
\b Matches a non word boundary.

Regular expressions commonly used in the JS method:
Copy Code code as follows:

/**
* Find the substring in the source string that satisfies the requirement.
* @return {}
*/
function Matchdemo () {
var r, re; Declare a variable.
var s = "The rain in Spain falls mainly in the plain";
Re = new RegExp ("Ain", "G"); Creates a regular expression object.
r = S.match (re); Finds a match in the string s.
return (R);
}

/**
* Returns all string and position information that satisfies the regular expression in the source string.
*/
function Regexptest () {
var ver = number (ScriptEngineMajorVersion () + "."
+ scriptengineminorversion ())
var ans = ';
if (ver >= 5.5) {//test the version of JScript.
var src = "The rain in Spain falls mainly the plain."
var re =/\w+/g; Creates a regular expression pattern.
var arr;
while ((arr = re.exec (src))!= null)
Ans + + Arr.index + "-" + Arr.lastindex + arr + "T";
} else {
Ans = "Please use the updated version of JScript";
}
return ans;
}

/**
* Check the source string for regular expressions to see if it fits the regular expression.
*/
function Testdemo () {
var S1;
var Source = "ABCDEFG";
var regex =/\w+/g; Creates a regular expression pattern.
if (regex.test (source))
S1 = "contains";
Else
S1 = "does not contain";
Return ("'" + Source + "'" + S1 + "'" + Regex.source + "");
}

/**
* Finds the string of regular expressions 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 worthwhile to learn and use good methods, call ():
Call ([thisobj[,arg1[, arg2[, [,. argn]]]]
Parameters
Thisobj
Options available. The object that will be used as the current object.
Arg1, Arg2, argn.
Options available. A sequence of method parameters is passed.
Description
The call method can be used to invoke 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.

A simple example:
Copy Code code as follows:

function Add (a,b)
{
alert (A+B);
}
function sub (a,b)
{
alert (a-b);
}

Add.call (sub,3,1);
The meaning of this example is to replace sub,add.call (sub,3,1) = Add (3,1) with add, so the result is: alert (4);

A slightly more complex example:
Copy Code code 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 the C2, the original C2 is not the Shownam () method, now is the C1 Shownam () method to carry out the C2, so this.name should be class2, the result of execution is: alert (" Class2 ");

Examples of multiple inheritance:
Copy Code code 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:
Function.apply (Obj,args) method can receive two parameters
OBJ: This object will replace the This object in the function class
Args: This is an array, which is passed as a parameter to the function (args-->arguments)
The effect of implementing a call-like inheritance:
Copy Code code as follows:

function Person (name,age) {//Define a class, human
This.name=name; Name
This.age=age; Age
This.sayhello=function () {alert ("Hello")};
}
function Print () {//Show properties of Class
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", 13, 6, "Tsinghua Primary School");
S1.show ();
S1.sayhello ();
alert (s1.funcname);

A cool way to optimize the function of an array parameter using apply:
Copy Code code as follows:

Math.max can be followed by any parameter, and finally returns the maximum value in all parameters.

Like what
Alert (Math.max (5,8))//8
Alert (Math.max (5,7,9,3,1,6))//9

But 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 the case. Be sure to write 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;
}

Apply it, look at the code:
function GetMax2 (arr) {
Return Math.max.apply (Null,arr);
}

Here is another example of merging two arrays:
Copy Code code as follows:

Another example is the push method of an array.
var arr1=[1,3,4];
var arr2=[3,4,5];
If we want to expand the arr2, and then one by one append to the arr1, finally let arr1=[1,3,4,3,4,5]
Arr1.push (ARR2) is clearly not a good one. Because doing so will get [1,3,4,[3,4,5]]

We can only use one loop to go one push (of course we can also use Arr1.concat (ARR2), but concat method does not change arr1 itself)
var arrlen=arr2.length
for (Var i=0;i<arrlen;i++) {
Arr1.push (Arr2[i]);
}

Use Apply words:
Copy Code code 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.