A practical method of JavaScript summarizing _javascript skills

Source: Internet
Author: User
Tags closure current time data structures rand setinterval string to number

Introduction:

This chapter is not esoteric to explain some of the underlying principles of JS, such as this pointer, scope, prototype, are involved in some of the normal development of the code to simplify, improve the efficiency of execution, or can be used as an empirical method to use, space is not long, small steps to let you read the full article, experience programming happiness.

Get random numbers within two intervals

Copy Code code as follows:

function Getrandomnum (Min, Max) {//Get random number within two intervals
@ The fire hurricane suggests it's possible that the first parameter is greater than the second parameter, so it's more reliable to increase the judgment
if (Min > Max)
Max = [min, min = max][0]; Fast swap two variable values

var Range = max-min + 1;
var Rand = Math.random ();
return Min + math.floor (Rand * Range);
};

Random return of a positive/negative parameter

Copy Code code as follows:

function Getrandomxy (num) {//random returns a positive/negative parameter
num = new number (num);
if (Math.random () <= 0.5)
num =-num;
return num;
}

SetInterval () or settimeout () Timer function argument

Copy Code code as follows:

var s = ' I am the parameter ';
function fn (args) {
Console.log (args);
}
var a = SetInterval (FN (s), 100); XXXXXX error xxxxx
var B = setinterval (function () {//correct, using anonymous function to call the timer function
FN (s);
}, 100);

SetInterval () or settimeout () timer recursive call

Copy Code code as follows:

var s = true;
function Fn2 (A, B) {//step three
if (s) {
Clearinterval (a);
Clearinterval (b);
}
};
function fn (a) {//Step two
var B = setinterval (function () {
Fn2 (A, B)//Incoming two timers
}, 200)
};
var a = setinterval (function () {//Step one
FN (a); b represents the timer itself and can be passed by seat parameters
}, 100);

Convert string to Number

Copy Code code as follows:

No new number (string) or number (string) is needed to subtract 0 from the string
var str = ' 100 '; Str:string
var num = str-0;//Num:number

Null value judgment

Copy Code code as follows:

var s = '; Empty string
The IF (!s)//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 code as follows:

The following conversion is 0 under IE, and 1 for other browsers, which is related to the interpretation of the digital system by IE browser
var inum = parseint (01);
So, the compatibility is written as
var num = parseint (new number (01));

Firebug Easy Debugging JS code

Copy Code code as follows:

Firebug built-in a console object that provides built-in methods for displaying information
/**
* 1:console.log (), which can be used instead of alert () or document.write () to support placeholder output, characters (%s), integers (%d or%i), floating-point numbers (%f), and Objects (%o). such as: Console.log ("%d years%d months%d days", 2011,3,26)
* 2: If the information is too much, can be displayed in groups, the method used is Console.group () and Console.groupend ()
* 3:CONSOLE.DIR () can display all the properties and methods of an object
* 4:console.dirxml () to display the Html/xml code contained in a node of a Web page
* 5:console.assert () assertion, used to determine whether an expression or variable is true
* 6:console.trace () used to track the call path of the function
* 7:console.time () and Console.timeend () to display the elapsed time of the code
* 8: Performance analysis (Profiler) is the analysis of the various parts of the operating time, to find the bottleneck, the use of the method is Console.profile () ... fn....console.profileend ()
*/

Quickly take the current number of milliseconds

Copy Code code as follows:

t = = Current system millisecond value, Reason: + operator will, call Date's valueof () method.
var t = +new Date ();

Quick Decimal integer digits

Copy Code code as follows:

x = 2, the following X values are 2, and negative numbers can also be converted
var x = 2.00023 | 0;
x = ' 2.00023 ' | 0;

Two variable value interchange (without intermediate amount)

Copy Code code as follows:

var a = 1;
var B = 2;
A = [B, b=a][0]
Alert (+ ' _ ' +b)//result 2_1,a and B have been swapped.

Logic or ' | | ' Operator

Copy Code code as follows:

B is not null:a=b, B is null:a=1.
var a = B | | 1;
A more common use is to pass a parameter for a plug-in method, and get the event target element: Events = Event | | Window.event
IE has window.event objects, but FF does not.

Only method objects have prototype stereotype properties

Copy Code code as follows:

Method has an object prototype prototype property, and the original data does not have the attribute, such as var a = 1, and A has no 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 at this time in the new operator.
P1.run (); Run ...

Quick get the day of the week

Copy Code code as follows:

The current time of the computing system is the week
var week = "Today is: Week" + "Day 123456". Charat (new Date (). Getday ());

Closed-pack bias

Copy Code code as follows:

/**
* Closure: Any JS method body can be called a closure, not what only the inline function to reference the external function of a parameter or attribute to occur.
* It has a separate scope in which several child scopes can exist (that is, the method nesting method), and eventually the closure scope is scoped to the outermost method
* It contains both the method parameters and the method parameters of all the inline functions, so when an inline function is referenced externally, the reference scope is scoped to the (top-level) method where the function is referenced
*/
function A (x) {
Function B () {
alert (x); referencing external function arguments
}
return b;
}
var run = A (' Run ... ');
Because of scope enlargement, you can refer to the variables of external function A and display
Run (); Alert (): Run ...

Get address parameter string and timed refresh

Copy Code code as follows:

Get a question mark? The following, including the question mark
var x = Window.location.search
Get the alarm # behind the contents, including the # number
var y = Window.location.hash
The matching timer can realize automatic refresh of webpage
Window.location.reload ();

null and undefined

Copy Code code as follows:

/**
* Undefined type has only one value, that is, undefined. The default value for a variable is undefined when the declared variable has not yet been initialized.
* A null type also has only one value, that is, null. Null is used to represent an object that does not exist, and is commonly used to represent a function attempt to return an object that does not exist.
* ECMAScript that undefined are 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 both of the following methods
* In the judgment when the need to determine whether the object has a value, it is best to use ' = = ' strong type judgment.
*/
var A;
Alert (A = = = null); False, because a is not an empty object
Alert (A = = = undefined); True because a is not initialized and the value is undefined
Extended
Alert (Null = = undefined); True because the ' = = ' operator makes type conversions,
Similarly
Alert (1 = ' 1 '); True
Alert (0 = false); True,false converted to Number type 0

To add parameters dynamically to a method

Copy Code code as follows:

Method A has one more argument 2
function A (x) {
var arg = Array.prototype.push.call (arguments,2);
Alert (arguments[0]+ ' __ ' +arguments[1]);
}

Custom Select Border Style

Copy Code code as follows:

<!--copy to the page to try the effect bar, you can customize the style-->
<span style= "border:1px solid red; Position:absolute; Overflow:hidden; ">
<select style= "MARGIN:-2PX;" >
<option> Custom Select border Style </option>
<option>222</option>
<option>333</option>
</select>
</span>

The simplest palette

Copy Code code as follows:

<!--JS to extract its value can set any color to any object Oh-->
<input type=color/>

Function, object is array?

Copy Code code as follows:

var anobject = {}; An object
Anobject.aproperty = "Property of Object"; An attribute of an object
Anobject.amethod = function () {alert ("Method of Object")}; A method of an object
Mainly look below:
Alert (anobject["Aproperty"]); You can access an object as an array by using the property name as the subscript
anobject["Amethod"] (); You can call a method by using the object as the subscript with the method name as the array
For (var s in anobject)//Traversal of all properties and methods of an object for iterative processing
Alert (S + "is a" + typeof (Anobject[s]));
The same is true for objects of function types:
var afunction = function () {}; a function
Afunction.aproperty = "property of function"; A property of a function
Afunction.amethod = function () {alert ("Method of Function")}; A method of a function
Mainly look below:
Alert (afunction["Aproperty"]); You can access a function as an array by using the property name as the subscript
afunction["Amethod"] (); Functions can be called by using the method name as the subscript in the array.
For (var s in afunction)//Traversal of all properties and methods of functions for iterative processing
Alert (S + "is a" + typeof (Afunction[s]));

Copy Code code as follows:

/**
* Yes, objects and functions can be accessed and processed in the same way as arrays, using property names or method names as subscripts.
* So, is it supposed to be an array or an object? We know that the array should be regarded as linear data structure, linear data structure generally have a certain regularity, suitable for unified batch iterative operation, a bit like waves.
* and objects are discrete data structures, suitable for describing dispersed and personalized things, a bit like particles.
* So we can also ask: Is the object in JavaScript a wave or a particle? If there is an object quantum theory, then the answer must be: wave-particle duality!
* Therefore, functions and objects in JavaScript have both object characteristics and array characteristics. The array here is called a "dictionary", a collection of name-value pairs that can be arbitrarily scaled. In fact, the internal implementation of object and function is a dictionary structure, but the dictionary structure shows a rich appearance through rigorous and ingenious syntax. Just as quantum mechanics interprets and deals with particles in some places, and in other places it uses waves to explain and deal with problems. You can also choose to use objects or arrays to interpret and handle problems when you need them. As long as you are good at mastering these wonderful features of JavaScript, you can write a lot of simple and powerful code.
*/

Clicking on the blank can trigger an element to close/hide

Copy Code code as follows:

/**
* Sometimes the page has a pull-down menu or something that requires the user to click on a blank or click on another element to hide it
* A global document Click event can be used to trigger
* @param {Object} ' target object '
*/
$ (document). Click (function (e) {
$ ("target object"). Hide ();
});
/**
* But one drawback is that when you click on the element and you want him to show
* If you don't stop the event bubbling to the Global departure Document object Click, the above method executes
*/
$ ("target object"). Click (Function (event) {
Event = Event | | window.event;
Event.stoppropagation (); Prevent event bubbles in time when clicking on target object
$ ("target object"). Toggle ();
});

The above is a personal summary of some of the javascript commonly used methods, I hope you can enjoy.

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.