Home Web Front-end JS Tutorial Summary of common JavaScript methods_Basic knowledge

Summary of common JavaScript methods_Basic knowledge

May 16, 2016 pm 04:29 PM
javascript Common methods

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

Copy code The code is as follows:

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

Copy code The code is as follows:

function getRandomXY(num){ // Randomly returns a positive/negative parameter
num = new Number(num);
If (Math.random() <= 0.5)
         num = -num;
Return num;
}

setInterval() or setTimeOut() timer function passing parameters

Copy code The code is as follows:

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

Copy code The code is as follows:

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

Copy code The code is as follows:

// 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

Copy code The code is as follows:

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

Copy code The code is as follows:

// 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

Copy code The code is as follows:

//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

Copy code The code is as follows:

// t == Current system millisecond value, reason: The sign operator will call the valueOf() method of Date.
var t = new Date();

Quickly get decimal places

Copy code The code is as follows:

// 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)

Copy code The code is as follows:

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

Copy code The code is as follows:

// 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

Copy code The code is as follows:

// 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

Copy code The code is as follows:

// 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

Copy code The code is as follows:

/**
* 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

Copy code The code is as follows:

// 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

Copy code The code is as follows:

/**
* 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

Copy code The code is as follows:

// 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

Copy code The code is as follows:






The simplest color palette

Copy code The code is as follows:



Function, object is array?

Copy code The code is as follows:

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]));

Copy code The code is as follows:

/**
* 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

Copy code The code is as follows:

/**
* 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.

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles