Home >Web Front-end >JS Tutorial >Collection of basic knowledge of javascript (2) Recommended collection_Basic knowledge

Collection of basic knowledge of javascript (2) Recommended collection_Basic knowledge

WBOY
WBOYOriginal
2016-05-16 18:11:551132browse

Look at the attached example in detail, it is relatively simple to write.


1. About cookie functions:

Copy code The code is as follows :

/**
* Cookie operation tool.
* Usage method: Save value: CookieTool('name','1',{expires: 7}) //Indicates saving a cookie with a value of 1 and a key value of name, which is invalid. 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. Regarding a js function that can view js objects, a cool method:
Copy the code The code is 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="
else{
str="";
}
var key=[];
for(var i in obj ){
key.push(i);
}
key.sort();
for(var i=0;ivar v= new String(obj[key[i]]).replace(//g,">");
str ="
";
}
str=str "
" key[i] "" v "
";
writeMsg(str);
}
function trace(v){
var str="
";
str =String(v).replace(//g ,">");
str ="
";
writeMsg(str);
}
function writeMsg(s) {
traceWin=window.open("","traceWindow","height=600, width=800,scrollbars=yes");
traceWin.document.write(s);
}
}

3. Regular expression:

g represents global matching
m represents multi-line matching
i represents case-insensitive matching
^ matching The start position of the input string
$ matches the end position of the input string
* matches the previous subexpression zero or more times. Equivalent to {0,}
matches the previous subexpression once or more times. Equivalent to {1,}
? Matches the preceding subexpression zero or one time. Equivalent to [0,1} when this character is followed by any other qualifier (*, , ? , {n}, {n,}, {n,m}) later, the matching pattern is non-greedy. Non-greedy mode matches as little of the searched string as possible, while the default greedy mode matches as much of the searched string as possible. For example, for the string "oooo", 'o ?' will match a single "o", while 'o ' will match all 'o's.

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 whitespace character, including spaces, tabs, and formfeeds Etc. Equivalent to [fnrtv]
S matches any non-whitespace character. Equivalent to [^frntv]
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 code The code is as follows:

/**
* Find substrings that meet the requirements in the source string.
* @return {}
*/
function MatchDemo() {
var r, re; // Declare variables.
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); // Find a match in string s.
return (r);
}

/**
* Returns all string and position information in the source string that satisfies the regular expression.
*/
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 a regular expression pattern.
var arr;
while ((arr = re.exec(src)) != null)
ans = arr.index "-" arr.lastIndex arr "t";
} else {
ans = "Please use an updated version of JScript";
}
return ans;
}

/**
* Perform a regular expression check on the source string to see if it conforms to the regular expression.
*/
function TestDemo() {
var s1;
var source = "abcdefg";
var regex = /w /g; // Create a regular expression pattern.
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 using a good method, call():
call([thisObj[,arg1[, arg2[, [,.argN]]] ]])
Parameters
thisObj
Optional. The object that will be used as the current object.
arg1, arg2, , argN
Optional. A sequence of method parameters will be passed.
Description
The call method can be used to call a method instead of another object. The call method changes the object context of a function from the initial context to the new object specified by thisObj.

Simple example:
Copy code The code is as follows:

function add (a,b)
{
alert(a b);
}
function sub(a,b)
{
alert(a-b);
}

add.call(sub,3,1);
//The meaning in this example is to replace sub with add, add.call(sub,3,1) == add(3,1), So the running result is: alert(4);

Slightly more complicated example:
Copy code The 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 method of c1 in Executed on c2. It turns out that c2 does not have a showNam() method. Now the showNam() method of c1 is put on c2 for execution, so this.name should be class2, and the execution result is: alert ("class2");

Example of multiple inheritance:
Copy code The 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:
Function. The apply(obj,args) method can receive two parameters
obj: This object will replace this object in the Function class
args: This is an array, which will be passed to Function as a parameter (args-->arguments)
Achieve the effect of call-like inheritance:
Copy code The code is 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(){ //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",13,6,"Tsinghua Primary School");
s1.show();
s1.sayhello();
alert(s1.funcName);

Use apply to optimize the function of array parameters, a cool method:
Copy the code The code is as follows:

Math.max can be followed by any number of parameters, and finally the maximum value among all parameters is returned.

For example
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 an array.
var arr=[5,7,9,1]
alert(Math.max(arr)) // This doesn’t work. Be sure to write it like this

function getMax(arr){
var arrLen=arr.length;
for(var i=0,ret=arr[0];iret=Math.max(ret,arr[i]);
}
return ret;
}

To use apply, look at the code:
function getMax2( arr){
return Math.max.apply(null,arr);
}

Here is another example to merge two arrays:
Copy code The code is 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 arr2, then append to arr1 one by one, and finally let arr1 =[1,3,4,3,4,5]
arr1.push(arr2) obviously does not work. Because doing this will get [1,3,4,[3,4,5]]

We can only use a loop to push one by one (of course you can also use arr1.concat(arr2), but The concat method does not change arr1 itself)
var arrLen=arr2.length
for(var i=0;iarr1.push(arr2[i]);
}

To use apply:
Copy the code The code is as follows:

Array.prototype.push.apply(arr1,arr2)

Package downloadhttp://xiazai.jb51.net/201101/yuanma/MyHtml.rar
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn