Summary of common JavaScript methods_Basic knowledge
This chapter does not provide a profound explanation of some of the underlying principles of js, such as this pointer, scope, and prototypes. It involves some things that are beneficial to simplifying code and improving execution efficiency during daily development, or can be used as an empirical method. , the length is not long, and you can read the entire article in small steps and experience the joy of programming.
Get random numbers within two intervals
function getRandomNum(Min, Max){ // Get random numbers within two intervals
// @ Backfire Crazy proposed that it is possible that the first parameter is greater than the second parameter, so adding a little more judgment is more reliable
If (Min > Max)
Max = [Min, Min = Max][0]; // Quickly exchange two variable values
var Range = Max - Min 1;
var Rand = Math.random();
Return Min Math.floor(Rand * Range);
};
Randomly returns a positive/negative parameter
function getRandomXY(num){ // Randomly returns a positive/negative parameter
num = new Number(num);
If (Math.random() num = -num;
Return num;
}
setInterval() or setTimeOut() timer function passing parameters
var s = 'I am a parameter';
function fn(args) {
console.log(args);
}
var a = setInterval(fn(s),100); // xxxxxx error xxxxx
var b = setInterval(function(){ // Correct, use anonymous function to call the timed function
fn(s);
}, 100);
setInterval() or setTimeOut() timer recursively calls
var s = true;
function fn2(a, b){ // Step 3
If (s) {
clearInterval(a);
clearInterval(b);
}
};
function fn(a){ // Step 2
var b = setInterval(function(){
fn2(a, b) // Pass in two timers
}, 200)
};
var a = setInterval(function(){ // Step 1
fn(a); // b represents the timer itself, which can be passed as a seat parameter
}, 100);
Convert string to number
// No need for new Number(String) nor Number(String). Just subtract zero from the string
var str = '100'; // str: String
var num = str - 0;// num: Number
Null value judgment
var s = ''; // Empty string
if(!s) // The empty string is converted to Boolean false by default and can be written directly in the judgment statement
if(s != null) // But empty string != null
if(s != undefined) // Empty string also != undefined
IE browser parseInt() method
// The following conversion is 0 in IE and 1 in other browsers. This is related to the base system used by the IE browser to interpret numbers
var iNum = parseInt(01);
// Therefore, the compatible writing method is
var num = parseInt(new Number(01));
Firebug conveniently debugs js code
//Firebug has a built-in console object that provides built-in methods to display information
/**
* 1: console.log(), which can be used to replace alert() or document.write(), supports placeholder output, characters (%s), integers (%d or %i), floating point numbers (%f) and object (%o). For example: console.log("%d year %d month %d day", 2011,3,26)
*2: If there is too much information, it can be displayed in groups. The methods used are console.group() and console.groupEnd()
*3: console.dir() can display all properties and methods of an object
* 4: console.dirxml() is used to display the html/xml code contained in a node of the web page
* 5: console.assert() assertion, used to determine whether an expression or variable is true
* 6: console.trace() is used to track the calling trace of the function
* 7: console.time() and console.timeEnd(), used to display the running time of the code
* 8: Performance analysis (Profiler) is to analyze the running time of each part of the program and find out where the bottleneck is. The method used is console.profile()....fn....console.profileEnd()
*/
Quickly get the current time in milliseconds
// t == Current system millisecond value, reason: The sign operator will call the valueOf() method of Date.
var t = new Date();
Quickly get decimal places
// x == 2, the following x values are all 2, negative numbers can also be converted
var x = 2.00023 | 0;
// x = '2.00023' | 0;
Interchange the values of two variables (no intermediate quantity is used)
var a = 1;
var b = 2;
a = [b, b=a][0]
alert(a '_' b) // Result 2_1, the values of a and b have been interchanged.
Logical OR '||' operator
// b is not null: a=b, b is null: a=1.
var a = b || 1;
// The more common usage is to pass parameters to a plug-in method and obtain the event target element: event = event || window.event
// IE has a window.event object, but FF does not.
Only method objects have prototype attributes
// The method has the object prototype prototype attribute, but the original data does not have this attribute, such as var a = 1, a does not have the prototype attribute
function Person() {} // Person constructor
Person.prototype.run = function() { alert('run...'); } // Prototype run method
Person.run(); // error
var p1 = new Person(); // Only when using the new operator, the prototype run method will be assigned to p1
p1.run(); // run...
Quickly get the day of the week
// Calculate the day of the week the current system time is
var week = "Today is: week" "Day one, two, three, four, five, six".charat(new date().getDay());
Closure bias
/**
* Closure: Any js method body can be called a closure. It does not only happen when an inline function refers to a parameter or attribute of an external function.
* It has an independent scope, within which there can be several sub-scopes (that is, method nested methods). In the end, the closure scope is the scope of the outermost method
* It includes its own method parameters and the method parameters of all embedded functions, so when an embedded function has an external reference, the scope of the reference is the (top-level) method scope where the referenced function is located
*/
function a(x) {
Function b(){
alert(x); // Reference external function parameters
}
Return b;
}
var run = a('run...');
// Due to the expansion of the scope, the variables of the external function a can be referenced and displayed
run(); // alert(): run..
Get address parameter string and refresh regularly
// Get question mark? The following content includes question marks
var x = window.location.search
// Get the content after the police number #, including the # number
var y = window.location.hash
// Use the timer to automatically refresh the web page
window.location.reload();
Null and Undefined
/**
* The Undefined type has only one value, which is undefined. When a declared variable has not been initialized, the variable's default value is undefined.
* The Null type also has only one value, which is null. Null is used to represent an object that does not yet exist. It is often used to indicate that a function attempts to return a non-existent object.
* ECMAScript believes that undefined is derived from null, so they are defined as equal.
* However, if in some cases, we must distinguish between these two values, what should we do? You can use the following two methods
* When making judgments, it is best to use '===' strong type judgment when judging whether an object has a value.
*/
var a;
alert(a === null); // false, because a is not an empty object
alert(a === undefined); // true, because a is not initialized, the value is undefined
// Extension
alert(null == undefined); // true, because the '==' operator will perform type conversion,
//Similarly
alert(1 == '1'); // true
alert(0 == false); // true, false are converted to Number type 0
Dynamically add parameters to the method
// Method a has one more parameter 2
function a(x){
var arg = Array.prototype.push.call(arguments,2);
alert(arguments[0] '__' arguments[1]);
}
Customized SELECT border style
The simplest color palette
Function, object is array?
var anObject = {}; //an object
anObject.aProperty = “Property of object”; //A property of the object
anObject.aMethod = function(){alert(“Method of object”)}; //A method of the object
//Mainly look at the following:
alert(anObject[“aProperty”]); //You can use the object as an array and use the property name as a subscript to access properties
anObject[“aMethod”](); //You can use the object as an array and use the method name as a subscript to call the method
for( var s in anObject) //Traverse all properties and methods of the object for iterative processing
alert(s ” is a ” typeof(anObject[s]));
// The same is true for objects of function type:
var aFunction = function() {}; //A function
aFunction.aProperty = “Property of function”; //A property of the function
aFunction.aMethod = function(){alert(“Method of function”)}; //A method of function
//Mainly look at the following:
alert(aFunction[“aProperty”]); //You can use the function as an array and use the attribute name as a subscript to access the attribute
aFunction[“aMethod”](); //You can use the function as an array and use the method name as a subscript to call the method
for(var s in aFunction) //Traverse all properties and methods of the function for iterative processing
alert(s ” is a ” typeof(aFunction[s]));
/**
* Yes, objects and functions can be accessed and processed like arrays, using property names or method names as subscripts.
* So, should it be considered an array or an object? We know that arrays should be regarded as linear data structures. Linear data structures generally have certain rules and are suitable for unified batch iteration operations. They are a bit like waves.
* Objects are discrete data structures, suitable for describing dispersed and personalized things, a bit like particles.
* Therefore, we can also ask: Are objects in JavaScript waves or particles? If there is a quantum theory of objects, then the answer must be: wave-particle duality!
* Therefore, functions and objects in JavaScript have the characteristics of both objects and arrays. The array here is called a "dictionary", a collection of name-value pairs that can be arbitrarily expanded. In fact, the internal implementation of object and function is a dictionary structure, but this dictionary structure shows a rich appearance through rigorous and exquisite syntax. Just as quantum mechanics uses particles to explain and deal with problems in some places, and waves in other places. You can also freely choose to use objects or arrays to explain and handle problems when needed. As long as you are good at grasping these wonderful features of JavaScript, you can write a lot of concise and powerful code.
*/
Clicking on a blank space can trigger a certain element to close/hide
/**
* Sometimes the page has a drop-down menu or some other effect, which requires the user to click on a blank space or click on other elements to hide it
* Can be triggered by a global document click event
* @param {Object} "Target object"
*/
$(document).click(function(e){
$("target object").hide();
});
/**
* But one disadvantage is that when you click on the element, you want it to display
* If you don’t stop the event from bubbling up to the global starting document object in time, the above method will be executed
*/
$("target object").click(function(event){
Event = event || window.event;
Event.stopPropagation(); // When the target object is clicked, stop the event from bubbling in time
$("target object").toggle();
});
The above are some commonly used javascript methods that I have compiled. I have recorded them for easy use during my own development. I also recommend them to friends in need.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


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

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SublimeText3 Linux new version
SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver CS6
Visual web development tools