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

Summary of common JavaScript methods_Basic knowledge

WBOY
Release: 2016-05-16 16:29:35
Original
1251 people have browsed it

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.

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template