JavaScript Application skills set [recommended] _ javascript skills

Source: Internet
Author: User
Some time ago I have collected and summarized the application skills in JavaScript. Here I will describe these application skills in a centralized manner. If you think you have missed some useful application skills, please leave a message and I will update it to this Article in time. Convert to Boolean type
All values in JavaScript can be implicitly converted to the Boolean type, for example:

The Code is as follows:

0 = false; // true 1 = true; // true ''= false // true null = false // true

However, these values are not of the Boolean type.
Therefore, when we use three equal signs for comparison:

The Code is as follows:

0 = false; // false 1 = true; // false ''= false // false null = false // false

The question now is how to convert other types to the Boolean Type:

The Code is as follows:

!! 0 = false; // true !! 1 = true; // true !! ''= False // true !! Null = false // true



Assign initial values to parameters
JavaScript does not support overload, but function parameters in JavaScript are optional. Undefined.

The Code is as follows:

Function plus (base, added) {return base + added;} plus (2); // NaN

In this example, Plus (2)And Plus (2, undefined)Is equivalent, 2 + undefinedThe result is NaN.
Now the question is, if the second parameter is not passed, how can we assign an initial value to it?

The Code is as follows:

Function plus (base, added) {added = added | 1; return base + added;} plus (2); // 3 plus (2, 2); // 4



Some netizens mentioned that plus (2, 0) = 3; indeed, it seems that some special processing needs to be done in this place:

The Code is as follows:

Function plus (base, added) {added = added | (added = 0? 0: 1); return base + added ;}



Prevent others from loading your page in Iframe
If your website becomes very popular, many websites want to link to your website, or even embed your webpage into its own Webpage Through IFrame.
This is not fun, so how can we prevent such behavior?

The Code is as follows:

If (top! = Window) {top. location. href = window. location. href ;}

This code should be placed on every page of your HeadIf you want to know that no one is using the baidu blog, you will know.


String replacement
String. prototype. replaceFunctions often confuse programmers who are very familiar with C # or Java.
For example:

The Code is as follows:

'Hello world, Hello world'. replace ('World', 'javascript '); // The result is "hello JavaScript, Hello world"

ReplaceThe first parameter of the function is a regular expression.
If you pass a string to the first parameter, only the matching string found in the first parameter is replaced.
To solve this problem, we can use a regular expression:

The Code is as follows:

'Hello world, Hello world'. replace (/world/g, 'javascript '); // The result is "hello JavaScript, Hello JavaScript"

We can also specify that case sensitivity is ignored during replacement:

The Code is as follows:

'Hello world, Hello world'. replace (/hello/gi, 'Hi'); // The result is "Hi world, Hi world"



Convert arguments to an array
Predefined variables in the function ArgumentsIt is not a real array, but an object similar to an array.
It has LengthAttribute, but there are no slice, push, sort and other functions, so how to make ArgumentsWhat about functions with these arrays?
That is, how to make ArgumentsInto a real array?

The Code is as follows:

Function args () {return []. slice. call (arguments, 0);} args (2, 5, 8); // [2, 5, 8]



Specify the second parameter for the parseInt function.
ParseIntThe number used to convert a string to an integer. Syntax:

The Code is as follows:

ParseInt (str, [radix])

The second parameter is optional and used to specify the first parameter in hexadecimal notation.
If the second parameter is not passed, follow the following rules:
-> If StrStarting with 0x, it is considered as hexadecimal.
-> If StrStarting with 0, it is considered to be in octal format.
-> Otherwise, it is considered to be in decimal format.
The following code will be confusing if you do not know the rules:

The Code is as follows:

ParseInt ('08'); // 0 parseInt ('08', 10); // 8


Therefore, to ensure security, you must ParseIntSpecify the second parameter.

Deletes an element from an array.
Maybe we can use DeleteTo:

The Code is as follows:

Var arr = [1, 2, 3, 4, 5]; delete arr [1]; arr; // [1, undefined, 3, 4, 5]

As you can see, DeleteIt cannot really delete an element in the array. The deleted element will be UndefinedThe length of the array does not change.

In fact, we can use SpliceFunction to delete elements in the array, as shown below:

The Code is as follows:

Var arr = [1, 2, 3, 4, 5]; arr. splice (1, 1); arr; // [1, 3, 4, 5]



Functions are also objects
In JavaScript, functions are also objects, because we can add attributes for functions.
For example:

The Code is as follows:

Function add () {return add. count ++;} add. count = 0; add (); // 0 add (); // 1 add (); // 2

For functions AddAdded CountAttribute to record the number of times this function is called.

Of course, this can be achieved in a more elegant way:

The Code is as follows:

Function add () {if (! Arguments. callee. count) {arguments. callee. count = 0;} return arguments. callee. count ++;} add (); // 0 add (); // 1 add (); // 2

Arguments. calleePoint to the currently running function.


Maximum Value in the array
How to find the maximum value in an array of all numbers can be simply done through loops:

The Code is as follows:

Var arr = [2, 3, 45, 12, 8]; var max = arr [0]; for (var I in arr) {if (arr [I]> max) {max = arr [I] ;}} max; // 45

Is there any other way? We all know that JavaScript has MathObjects to process numbers:

The Code is as follows:

Math. max (2, 3, 45, 12, 8); // 45

Then, we can find the maximum value in the array as follows:

The Code is as follows:

Var arr = [2, 3, 45, 12, 8]; Math. max. apply (null, arr); // 45



Add for IEConsole. logFunction
We often use Firebug in Firefox. Console. logTo record some information in the console.
However, this method will block JavaScript Execution in IE (the same is true if Firebug is not enabled in Firefox), because there is no ConsoleObject exists.
We can use the following tips to prevent such a situation:

The Code is as follows:

If (typeof (console) ==='undefined') {window. console ={ log: function (msg) {alert (msg) ;}}}console. log ('debug info. ');



UndefinedIs it a reserved keyword in JavaScript?
It looks like yes, but in fact undefined is not a keyword in JavaScript:

The Code is as follows:

Var undefined = 'hello'; undefined; // 'hello'

This code may surprise you, but it does work properly, UndefinedIt's just a predefined variable in JavaScript.
Note: In JavaScript programs, do not do this. This technique only tells you the same thing.


Determines whether a variable is undefined.
In either case, a variable is undefined:
1. variables are declared, but no value is assigned.

The Code is as follows:

Var name; name = undefined; // true

2. This variable has never been declared

The Code is as follows:

Name2 === undefined; // error-name2 is not defined

In the second case, an error is thrown. If a variable is undefined and no error is generated?
The following provides a general method:

The Code is as follows:

Typeof (name2) ==='undefined'; // true



Preload Images
Preload images are images that do not exist on the page, so that they can be quickly displayed using JavaScript later.
For example, if you want to show another image when you move the mouse over an image:

The Code is as follows:

Var img = new Image (); img. src = "clock2.gif ";

The Code is as follows:


So how to load a group of images? Consider the following code:

The Code is as follows:

Var source = require 'img1.gif ']; var img = new Image (); for (var I = 0; I <source. length; I ++) {img. src = source [I];}

In fact, this code can only pre-load the last image, because other images do not have time to pre-load when the loop comes.
Therefore, the correct statement should be:

The Code is as follows:

Var source = require 'img1.gif ']; for (var I = 0; I <source. length; I ++) {var img = new Image (); img. src = source [I];}



Closure (closure)
Closure refers to the local variable in the function. This variable is still available when the function returns.
When you define another function inside the function, you create a closure, a famous example:

The Code is as follows:

Function add (I) {return function () {return ++ I ;}}add (2 ). toString (); // "function () {return ++ I;}" add (2) (); // 3

Add (2)Is a function that may obtain local variables of an external function. I.
References


Private variable
We often use naming conventions to indicate whether a variable is a private variable (most commonly used ):

The Code is as follows:

Var person = {_ name: '', getName: function () {return this. _ name | 'not defined' ;}}; person. getName (); // "not defined"

The underline prefix is used as a convention for private variables, but other developers can still call this private variable:

The Code is as follows:

Person. _ name ;//""

So, how to create a real private variable in JavaScript?
The main technique is to use an anonymous function and a closure ).

The Code is as follows:

Var person = {}; (function () {var _ name = ''; person. getName = function () {return _ name | 'not defined' ;}}) (); person. getName (); // "not defined" typeof (person. _ name); // "undefined"



JavaScript does not have block-level context (Scope)
In JavaScript, block-level code has no context. In fact, only functions have their own context.

The Code is as follows:

For (var I = 0; I <2; I ++) {} I; // 2

To create a context, use the self-executed anonymous function:

The Code is as follows:

(Function () {for (var I = 0; I <2; I ++) {}}) (); typeof (I) === 'undefined '; // true



Weird NaN
NaN is used to indicate that a value is not a number.
NaN acts strangely in JavaScript because NaN is not equal to any value (including itself ).

The Code is as follows:

NaN = NaN; // false

The following code may drive some people crazy:

The Code is as follows:

ParseInt ('hello', 10); // NaN parseInt ('hello', 10) = NaN; // false parseInt ('hello', 10) = NaN; // false

So how to check whether a value is NaN?
You can use window. isNaN to determine:

The Code is as follows:

IsNaN (parseInt ('hello', 10); // true



True and false values
All values in JavaScript can be implicitly converted to the Boolean type.
In condition determination, the following values are automatically converted to false:
Null, undefined, NaN, 0, '', false
Therefore, the following complex judgment is not required:

The Code is as follows:

If (obj = undefined | obj = null ){}

You only need to do this:

The Code is as follows:

If (! Obj ){}



Modify arguments
For example, add a value to arguments:

The Code is as follows:

Function add () {arguments. push ('new value');} add (); // error-arguments. push is not a function

This will cause errors because ArgumentsIt is not a real array and there is no push method.
Solution:

The Code is as follows:

Function add () {Array. prototype. push. call (arguments, 'new value'); return arguments;} add () [0]; // "new value"



Boolean and new Boolean
We can regard Boolean as a function to generate a Boolean value (Literal ):

The Code is as follows:

Boolean (false) = false; // true Boolean ('') = false; // true

So, Boolean (0)And !! 0Is equivalent.
We can also regard Boolean as a constructor. NewCreate a Boolean object:

The Code is as follows:

New Boolean (false) = false; // false new Boolean (false) = false; // true typeof (new Boolean (false )); // "object" typeof (Boolean (false); // "boolean"



Fast string connection
We often use +Concatenate a short string into a long string, which is normal in most cases.
However, if a large number of strings need to be connected, this method will encounter performance problems, especially in IE.

The Code is as follows:

Var startTime = new Date (); var str = ''; for (var I = 0; I <50000; I ++) {str + = I ;} alert (new Date ()-startTime); // Firefox-18 ms, IE7-2060 ms

The Code is as follows:

Var startTime = new Date (); var arr = []; for (var I = 0; I <100000; I ++) {arr. push (I);} var str = arr. join (""); alert (new Date ()-startTime); // Firefox-38 ms, IE7-280 ms


As you can see, Firefox seems to be +The operator is optimized, While IE is dumb.

Unary operator +
In JavaScript, we can use the unary operator "+" before the string ". This will convert the string to a number. If the conversion fails, NaN is returned.

The Code is as follows:

2 + '1'; // "21" 2 + (+ '1'); // 3

If + is used before a non-string, the conversion will be attempted in the following order:
    Call valueOf () call toString () to convert to a number

The Code is as follows:

+ New Date; // 1242616452016 + new Date = new Date (). getTime (); // true + new Date () = Number (new Date) // true

References


EncodeURI and encodeURIComponent
The window. encodeURI function is used to encode a URL, but does not encode the following characters: ":", "/", ";", "?".
Window. encodeURIComponent encodes the preceding characters.
Here is an example:

The Code is as follows:

'Index. jsp? Page = '+ encodeURI ('/page/home. jsp '); // "index. jsp? Page =/page/home. jsp "'index. jsp? Page = '+ encodeURIComponent ('/page/home. jsp '); // "index. jsp? Page = % 2 Fpage % 2Fhome. jsp"

Therefore, we often choose encodeURIComponent when encoding the URL.


Table. innerHTML is a read-only attribute in IE.
We often use InnerHTMLAttribute to fill nodes, such:

The Code is as follows:

The Code is as follows:

Document. getElementById ('container1'). innerHTML = "Hello World! ";

But set it in IE Table. innerHTMLThis will cause an error:

The Code is as follows:

The Code is as follows:

// Works well in Firefox, but fail to work in IE document. getElementById ('table1'). innerHTML ="HelloWorld!";

In fact, the innerHTML attributes of table, thead, tr, select, and other elements are read-only in IE.

If you create a table dynamically, the following provides a feasible method:

The Code is as follows:

The Code is as follows:

Document. getElementById ('table1'). innerHTML ="

Hello World!
";



0.1 + 0.2! = 0.3
JavaScript treats decimals as floating point numbers, so some rounding errors may occur, such:

The Code is as follows:

0.1 + 0.2; // 0.30000000000000004

You can use the toFixed method to specify the number of decimal places:

The Code is as follows:

(0.1 + 0.2). toFixed (); // "0" (0.1 + 0.2). toFixed (1); // "0.3"

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.