Summary of practical javascript methods and practical javascript methods

Source: Internet
Author: User
Tags time in milliseconds

Summary of practical javascript methods and practical javascript methods

Introduction:

This chapter does not provide an in-depth explanation of some underlying js principles, such as this pointer, scope, and prototype. It involves some of the underlying principles that help simplify code and improve execution efficiency during normal development, or it can be used as an empirical method, and the length is not long. It allows you to read the entire article and experience the joy of programming.

Returns a random number within two intervals.

Copy codeThe Code is as follows:
Function getRandomNum (Min, Max) {// obtain a random number within two intervals
// @ It is suggested that the first parameter may be greater than the second parameter, so it is more reliable to add a parameter.
If (Min> Max)
Max = [Min, Min = Max] [0]; // fast exchange of two variable values

Var Range = Max-Min + 1;
Var Rand = Math. random ();
Return Min + Math. floor (Rand * Range );
};

Returns a random positive/negative parameter.

Copy codeThe Code is as follows:
Function getRandomXY (num) {// a positive/negative parameter is randomly returned.
Num = new Number (num );
If (Math. random () <= 0.5)
Num =-num;
Return num;
}

SetInterval () or setTimeOut () timer function

Copy codeThe Code is as follows:
Var s = 'parameters I ';
Function fn (args ){
Console. log (args );
}
Var a = setInterval (fn (s), 100); // xxxxxx error xxxxx
Var B = setInterval (function () {// correct. Use an anonymous function to call the timed function.
Fn (s );
},100 );

SetInterval () or setTimeOut () timer recursive call

Copy codeThe Code is as follows:
Var s = true;
Function fn2 (a, B) {// step 3
If (s ){
ClearInterval ();
ClearInterval (B );
}
};
Function fn (a) {// Step 2
Var B = setInterval (function (){
Fn2 (a, B) // input two timers
}, 200)
};
Var a = setInterval (function () {// Step 1
Fn (a); // B indicates the timer itself, which can be passed by the seat parameter.
},100 );

Convert string to numeric

Copy codeThe Code is as follows:
// No new Number (String) or Number (String) is required. You only need to subtract zero from the String.
Var str = '000000'; // str: String
Var num = str-0; // num: Number

Null Value Judgment

Copy codeThe Code is as follows:
Var s = ''; // empty string
If (! S) // empty strings are converted to boolean false by default, which can be written directly in the judgment statement.
If (s! = Null) // but an empty string! = Null
If (s! = Undefined) // empty string! = Undefined

IE browser parseInt () method

Copy codeThe Code is as follows:
// The following conversion is 0 in IE and 1 in other browsers, which is related to the conversion of numbers in IE.
Var iNum = parseInt (01 );
// Therefore, the compatible format is
Var num = parseInt (new Number (01 ));

Convenient debugging of js code using Firebug

Copy codeThe Code is as follows:
// Firebug has a built-in console object that provides built-in methods for displaying information.
/**
* 1: console. log (), which can be used to replace alert () or document. write (), supporting placeholder output, characters (% s), integers (% d or % I), floating point numbers (% f), and objects (% o ). For example, console. log ("% d, % d, % d", 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 () displays all attributes and methods of an object.
* 4: console. dirxml () is used to display the html/xml Code contained by a node on a webpage.
* 5: console. assert () Assertions used to determine whether an expression or variable is true
* 6: console. trace () is used to track the call track of a function.
* 7: console. time () and console. timeEnd () are used to display the code running time.
* 8: Performance Analysis (Profiler) is used to analyze the running time of each part of the program and locate the bottleneck. The console is used. profile ().... fn .... console. profileEnd ()
*/

Quick query of the current time in milliseconds

Copy codeThe Code is as follows:
// T = Current System millisecond value. cause: the + operator will call the valueOf () method of Date.
Var t = + new Date ();

Fast decimal integer

Copy codeThe Code is as follows:
// X = 2. The following x values are both 2, and negative numbers can also be converted.
Var x = 2.00023 | 0;
// X = '2. 00023 '| 0;

Two variable values are exchanged (no intermediate amount is required)

Copy codeThe 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 exchanged.

Logical or '|' Operator

Copy codeThe Code is as follows:
// B is not null: a = B, B is null: a = 1.
Var a = B | 1;
// A common usage is to pass parameters in 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 codeThe Code is as follows:
// The method has the prototype attribute of the object prototype, but the original data does not have this attribute. For example, var a = 1 and a does not have the prototype attribute.
Function Person () {}// human Constructor
Person. prototype. run = function () {alert ('run... ');} // prototype run Method
Person. run (); // error
Var p1 = new Person (); // The prototype run method is assigned to p1 only when the new operator is used.
P1.run (); // run...

Get the day of the week quickly

Copy codeThe Code is as follows:
// The current computing system time is the day of the week
Var week = "today is: week" + "May 25, 1234". charat (new date (). getDay ());

Closure bias

Copy codeThe Code is as follows:
/**
* Closure: Any js method body can be called a closure. It does not happen only when an embedded function references a parameter or attribute of an external function.
* It has an independent scope. In this scope, there can be several sub-scopes (that is, the method nesting method), and the closure scope is the scope of the outermost method.
* It contains its own method parameters and the method parameters of all embedded functions. Therefore, when an embedded function is referenced externally, the reference scope is the (top-level) method scope of the referenced function.
*/
Function a (x ){
Function B (){
Alert (x); // reference external function parameters
}
Return B;
}
Var run = a ('run ...');
// Due to the extended scope, variables of external function a can be referenced and displayed.
Run (); // alert (): run ..

Obtain Address parameter strings and regularly refresh

Copy codeThe Code is as follows:
// Obtain the question mark? The following content, including question marks
Var x = window. location. search
// Obtain the content following the alert number #, including #
Var y = window. location. hash
// Use the timer to automatically refresh the webpage
Window. location. reload ();

Null and Undefined

Copy codeThe Code is as follows:
/**
* The Undefined type has only one value, that is, undefined. When the declared variable has not been initialized, the default value of the variable is undefined.
* The Null type also has only one value, that is, null. Null indicates an existing object. It is often used to indicate that a function attempts to return a non-existing object.
* ECMAScript considers undefined to be derived from null, so they are defined as equal.
* But what should we do if we need to differentiate the two values in some cases? You can use the following two methods:
* When determining whether an object has a value based on your needs, use the '=' type to determine whether the object has a value.
*/
Var;
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 performs type conversion,
// Likewise
Alert (1 = '1'); // true
Alert (0 = false); // true, false converted to Number type 0

Dynamically add parameters to a method

Copy codeThe Code is as follows:
// Method a has an additional parameter 2
Function a (x ){
Var arg = Array. prototype. push. call (arguments, 2 );
Alert (arguments [0] + '_' + arguments [1]);
}

Customize the SELECT border Style

Copy codeThe Code is as follows:
<! -- Copy to the page and try the effect. You can customize the style at will -->
<Span style = "border: 1px solid red; position: absolute; overflow: hidden;">
<Select style = "margin:-2px;">
<Option> customize the SELECT border style </option>
<Option> 222 </option>
<Option> 333 </option>
</Select>
</Span>

The simplest color palette

Copy codeThe Code is as follows:
<! -- JS extracts its value to set any color for any object -->
<Input type = color/>

Is an array of functions and objects?

Copy codeThe Code is as follows:
Var anObject ={}; // an object
AnObject. aProperty = "Property of object"; // an attribute of the object
AnObject. aMethod = function () {alert ("Method of object")}; // a Method of the object
// Mainly refer to the following:
Alert (anObject ["aProperty"]); // you can use the attribute name as the subscript to access the attribute when the Array
AnObject ["aMethod"] (); // you can call a method when the array uses the method name as the subscript.
For (var s in anObject) // iterate through all attributes and methods of the object
Alert (s + "is a" + typeof (anObject [s]);
// The same for function objects:
Var aFunction = function () {}; // a function
AFunction. aProperty = "Property of function"; // an attribute of a function
AFunction. aMethod = function () {alert ("Method of function")}; // a function Method
// Mainly refer to the following:
Alert (aFunction ["aProperty"]); // you can use the attribute name as the subscript of the array to access the attribute.
AFunction ["aMethod"] (); // you can call a method when the array uses the method name as the subscript.
For (var s in aFunction) // iterate through all attributes and methods of the Function
Alert (s + "is a" + typeof (aFunction [s]);

Copy codeThe Code is as follows:
/**
* Yes. Objects and functions can be accessed and processed using attribute names or method names as subscripts like arrays.
* Should it be an array or an object? As we know, arrays should be regarded as linear data structures. Linear data structures generally have certain rules and are suitable for uniform batch iteration operations, which is a bit like a wave.
* Objects are discrete data structures, which are suitable for describing scattered and personalized things, a bit like particles.
* Therefore, we can also ask: is the object in JavaScript a wave or a particle? If there is an object quantum theory, the answer must be: wave-particle binary!
* Therefore, functions and objects in JavaScript have both Object Features and array features. The array here is called a "Dictionary", a set of name-value pairs that can be scaled at will. In fact, the internal implementation of objects and functions is a dictionary structure, but this dictionary structure shows a rich appearance through rigorous and sophisticated syntax. Just as quantum mechanics uses particles in some places to explain and solve problems, while in other places it uses waves to explain and handle problems. You can also choose whether to use objects or arrays to explain and handle problems as needed. As long as you are good at understanding these wonderful features of JavaScript, you can write a lot of simple and powerful code.
*/

Clicking a blank space triggers the close/hide of an element.

Copy codeThe Code is as follows:
/**
* Sometimes the page has a drop-down menu or something. You need to click a blank space or another element to hide it.
* Triggered by a global document Click Event
* @ Param {Object} "target Object"
*/
$ (Document). click (function (e ){
$ ("Target object"). hide ();
});
/**
* But one drawback is that when you click this element, you want it to be displayed.
* If you do not timely prevent the event from bubbling to the global starting document Object clicking, the above method will be executed
*/
$ ("Target object"). click (function (event ){
Event = event | window. event;
Event. stopPropagation (); // when a target object is clicked, the event bubble is blocked in time.
$ ("Target object"). toggle ();
});

The above are some common javascript methods I have summarized. I hope you will like them.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.