


Collection of basic knowledge of javascript (2) Recommended collection_Basic knowledge
Look at the attached example in detail, it is relatively simple to write.
1. About cookie functions:
/**
* 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 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:
/**
* 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="
writeMsg(str); } function trace(v){ var 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];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;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 |

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 English version
Recommended: Win version, supports code prompts!

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver Mac version
Visual web development tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.
