45 kinds of JavaScript skills Daquan

Source: Internet
Author: User

JavaScript is a world-leading programming language for Web development, mobile application development (PHONEGAP, Appcelerator), server-side development (node. js and Wakanda), and more. JavaScript is also the first language for many beginners to step into the programming world. It can be used to display a simple cue box in a browser or to control a robot by Nodebot or Nodruino. Developers who can write well-structured, performance-efficient JavaScript code are now the most sought after in the recruiting market.

In this article, I'll share some of the JavaScript tips, tricks, and best practices that apply, with the exception of a few, whether it's a browser's JavaScript engine or a server-side JavaScript interpreter.

The sample code in this article has been tested on the latest version of Google Chrome 30 (V8 3.20.17.15).

1. Be sure to use the var keyword when assigning a variable for the first time

Variables are not declared and are directly assignable, and as a new global variable by default, avoid using global variables as much as possible.

2, use = = = Replace = =

The = = and! = operators automatically convert data types when needed. but = = = and!== do not, they compare values and data types at the same time, which makes them faster than = = and! =.

[ten] = = = =//Is False

[Ten] = =//Is True

' Ten ' = =//Is True

' = = = =/= False

[] = = 0//Is True

[] = = = 0//Is False

' = = False//is true but true = = "A" is false

' = = = False//is False

3, underfined, NULL, 0, False, NaN, the logical result of an empty string is False

4. Use a semicolon at the end of the line

In practice it is best to use a semicolon, forget to write it is OK, most of the case the JavaScript interpreter will be automatically added. For reasons to use semicolons, refer to the article JavaScript for the truth about semicolons.

5. Using the Object Builder

function person (firstName, lastName) {

This.firstname = FirstName;

This.lastname = LastName;

}

var Saad = new Person ("Saad", "Mousliki");

6. Use typeof, instanceof and contructor with care

The Typeof:javascript unary operator, which returns the original type of the variable as a string, note that typeof null also returns object, and most of the object types (array arrays, time date, and so on) also return an object

Contructor: Internal prototype properties, which can be overridden by code

The instanceof:javascript operator, which is searched in the constructor in the prototype chain, returns true if found, otherwise false

var arr = ["A", "B", "C"];

typeof Arr; Returns "Object"

Arr instanceof Array//True

Arr.constructor (); //[]

7. Using the self-calling function

Functions are executed automatically after they are created, often referred to as self-invoking anonymous functions (self-invoked Anonymous function) or directly calling function expressions (Immediately invoked functions expression). The format is as follows:

(function () {

The code placed here will be executed automatically

})();

(function (A, b) {

var result = A+b;

return result;

}) (10,20)

8. Get members randomly from the array

var items = [548, ' a ', 2, 5478, ' foo ', 8852,, ' Doe ', 2145, 119];

var Randomitem = Items[math.floor (Math.random () * items.length)];

9. Get random numbers within a specified range

This feature has a special number when generating false data for testing, such as the number of wages in a given range.

var x = Math.floor (Math.random () * (Max-min + 1)) + min;

10. Generate a numeric array from 0 to a specified value

var numbersarray = [], max = 100;

for (var I=1; Numbersarray.push (i++) < Max;);//numbers = [... 100]

11. Generate a random alphanumeric string

function Generaterandomalphanum (len) {

var rdmstring = "";

for (; rdmstring.length < len; rdmstring + = Math.random (). toString (. substr (2));

Return rdmstring.substr (0, Len);

}

12. Scramble the order of the array of numbers

var numbers = [5, 458, 120,-215, 228, 400, 122205,-85411];

Numbers = Numbers.sort (function () {return math.random ()-0.5});

/* Numbers array will resemble [120, 5, 228,-215, 400, 458,-85411, 122205] */

The JavaScript built-in array sorting function is used here, and a better approach is to implement it with specialized code (such as the Fisher-yates algorithm), which can be found in the discussion on StackOverflow.

13, string to go to space

Languages such as Java, C #, and PHP implement specialized string de-whitespace functions, but there is no JavaScript in which you can use the following code to function as a trim function for a string object:

String.prototype.trim = function () {return this.replace (/^\s+|\s+$/g, "");};

The new JavaScript engine already has a native implementation of trim ().

14. Append between arrays

var array1 = [N, "foo", {name "Joe"},-2458];

var array2 = ["Doe", 555, 100];

Array.prototype.push.apply (Array1, array2);

/* Array1 value for [+, ' foo ', {name ' Joe '}, -2458, ' Doe ', 555, 100] */

15. Object conversions to arrays

var Argarray = Array.prototype.slice.call (arguments);

16, verify whether the number

function Isnumber (n) {

Return!isnan (parsefloat (n)) && isfinite (n);

}

17. Verify that it is an array

function IsArray (obj) {

return Object.prototype.toString.call (obj) = = = ' [Object Array] ';

}

But if the ToString () method is rewritten, it won't work. You can also use the following methods:

Array.isarray (obj); Its a new Array method

If you do not use a frame in your browser, you can also use instanceof, but if the context is too complex, there may be an error.

var myframe = document.createelement (' iframe ');

Document.body.appendChild (MyFrame);

var myArray = window.frames[window.frames.length-1]. Array;

var arr = new MyArray (a,b,10); [a,b,10]

MyArray The constructor has been lost, the result of instanceof will not be normal

Constructors are not shared across a frame

Arr instanceof Array; False

18. Get the maximum and minimum values in the array

var numbers = [5, 458, 120,-215, 228, 400, 122205,-85411];

var maxinnumbers = Math.max.apply (Math, numbers);

var mininnumbers = Math.min.apply (Math, numbers);

19. Empty the array

var myArray = [12, 222, 1000];

myarray.length = 0; MyArray'll is equal to [].

20. Do not delete or remove elements directly from the array

If you use delete directly on an array element, it is not actually deleted, just the element is set to undefined. array element deletions should use splice.

Avoid:

var items = [548, ' a ', 2, 5478, ' foo ', 8852,, ' Doe ', 2154, 119];

Items.length; Return 11

Delete Items[3]; return True

Items.length; Return 11

/* Items results for [548, "a", undefinedx1, 5478, "foo", 8852, Undefinedx1, "Doe", 2154, 119] */

Instead, you should:

var items = [548, ' a ', 2, 5478, ' foo ', 8852,, ' Doe ', 2154, 119];

Items.length; Return 11

Items.splice (3,1);

Items.length; Return 10

/* Items results for [548, "a", 5478, "foo", 8852, Undefinedx1, "Doe", 2154, 119]

You can use delete when you delete an object's properties.

21. Truncating an array with the Length property

The previous example empties the array with the length property, which is also used to truncate the array:

var myArray = [12, 222, 1000, 124, 98, 10];

Myarray.length = 4; MyArray'll is equal to [12, 222, 1000, 124].

At the same time, if you make the length property larger, the value of the array will increase, and the undefined will be used as the new element fill. Length is a writable property.

Myarray.length = 10; The new array length is 10

MYARRAY[MYARRAY.LENGTH-1]; Undefined

22. Use logic and or in conditions

var foo = 10;

Foo = && dosomething (); Is the same thing as if (foo = =) dosomething ();

Foo = = 5 | | DoSomething (); Is the same thing as if (foo! = 5) dosomething ();

Logic or can also be used to set default values, such as default values for function parameters.

function DoSomething (arg1) {

Arg1 = Arg1 | | 10; Arg1 would has ten as a default value if it ' s not already set

}

23, make map () function method to the data loop

var squares = [1,2,3,4].map (function (val) {

Return Val * val;

});

Squares'll be equal to [1, 4, 9, 16]

24. Keep the specified number of decimal digits

var num = 2.443242342;

num = num.tofixed (4); num'll be equal to 2.4432

Note that tofixec () returns a string, not a number.

25, floating point calculation problem

0.1 + 0.2 = = = 0.3//Is False

9007199254740992 + 1//is equal to 9007199254740992

9007199254740992 + 2//is equal to 9007199254740994

Why is it? Because 0.1+0.2 equals 0.30000000000000004. JavaScript numbers are built on the IEEE 754 standard and are internally represented by 64-bit floating-point decimals, as described in how numbers in JavaScript are encoded.

You can solve this problem by using tofixed () and toprecision ().

26. Check the properties of the object through the for-in loop

The following usage can prevent the iteration from entering the object's prototype properties.

for (var name in object) {

if (Object.hasownproperty (name)) {

Do something with Name

}

}

27. Comma operator

var a = 0;

var B = (a++, 99);

Console.log (a); A'll is equal to 1

Console.log (b); B is equal to 99

28. Temporarily store variables for calculations and queries

In the jquery selector, you can temporarily store the entire DOM element.

var navright = document.queryselector (' #right ');

var navleft = document.queryselector (' #left ');

var navup = document.queryselector (' #up ');

var navdown = document.queryselector (' #down ');

29. Check the parameters of incoming isfinite () in advance

Isfinite (0/0); False

Isfinite ("foo"); False

Isfinite ("10"); True

Isfinite (10); True

Isfinite (undefined); False

Isfinite (); False

Isfinite (NULL); True, this is when special attention is paid to

30. Avoid using negative numbers in the array to index

var numbersarray = [1,2,3,4,5];

var from = Numbersarray.indexof ("foo"); From is equal to-1

Numbersarray.splice (from,2); would return [5]

Note that the index parameter passed to splice is not a negative number, and when it is negative, the element is removed from the end of the array.

31. Serialization and deserialization with JSON

var person = {name: ' Saad ', age:26, department: {id:15, Name: ' R '}};

var Stringfromperson = json.stringify (person);

/* Stringfromperson result for ' {' name ': ' Saad ', ' age ': ', ' Department ': {' ID ': ' "Name ':" R/r}} "*/

var personfromstring = Json.parse (Stringfromperson);

/* The value of personfromstring is the same as the person object */

32. Do not use eval () or function constructor

The cost of Eval () and the function Consturctor are large, and each invocation of the JavaScript engine translates the source code into executable code.

var func1 = new Function (Functioncode);

var Func2 = eval (functioncode);

32. Do not use eval () or function constructor

The cost of Eval () and the function Consturctor are large, and each invocation of the JavaScript engine translates the source code into executable code.

var func1 = new Function (Functioncode);

var Func2 = eval (functioncode);

33. Avoid using with ()

using with () allows you to add variables to the global scope, so if there are other variables of the same name, one is easily confused and the values are overwritten.

34, do not use for-in array

Avoid:

var sum = 0;

for (var i in arraynumbers) {

Sum + = Arraynumbers[i];

}

But:

var sum = 0;

for (var i = 0, len = arraynumbers.length; i < Len; i++) {

Sum + = Arraynumbers[i];

}

Another benefit is that I and Len two variables are in the first declaration of the For Loop, and they are initialized only once, which is faster than this:

for (var i = 0; i < arraynumbers.length; i++)

35. Use functions instead of strings when passed to SetInterval () and settimeout ()

If passed to SetTimeout () and SetInterval () a string, they will be converted in a similar way to Eval, which will certainly be slower, so do not use:

SetInterval (' dosomethingperiodically () ', 1000);

SetTimeout (' Dosomethingafterfiveseconds () ', 5000);

Instead, use:

SetInterval (dosomethingperiodically, 1000);

SetTimeout (Dosomethingafterfiveseconds, 5000);

36, use Switch/case instead of a large stack of if/else

It is faster to use switch/case when judging more than two branches, but also more elegant, more conducive to the organization of the Code, of course, if there are more than 10 branches, do not use Switch/case.

37. Using the digital range in Switch/case

In fact, the case condition in Switch/case can also be written like this:

function GetCategory (age) {

var category = "";

Switch (TRUE) {

Case IsNaN (age):

Category = "Not a age";

Break

Case (age >= 50):

Category = "old";

Break

Case (age <= 20):

Category = "Baby";

Break

Default

Category = "Young";

Break

};

return category;

}

GetCategory (5); will return "Baby"

38. Using objects as prototypes of objects

This allows you to create a new object that is prototyped with the given object as a parameter:

function Clone (object) {

function Oneshotconstructor () {};

Oneshotconstructor.prototype = object;

return new Oneshotconstructor ();

}

Clone (Array). prototype; // []

39. HTML Field conversion function

function escapehtml (text) {

var replacements= {"<": "<", ">": ">", "&": "&", "\" ":" ""};

Return Text.replace (/[<>& "]/g, function (character) {

return Replacements[character];

});

}

40. Do not use try-catch-finally inside the loop

The catch section in Try-catch-finally assigns an exception to a variable when it is executed, which is constructed as a new variable within the runtime scope.

Avoid:

var object = [' foo ', ' Bar '], I;

for (i = 0, len = object.length; I <len; i++) {

try {

Do something this throws an exception

}

catch (e) {

Handle exception

}

}

Instead, you should:

var object = [' foo ', ' Bar '], I;

try {

for (i = 0, len = object.length; I <len; i++) {

Do something this throws an exception

}

}

catch (e) {

Handle exception

}

41. When using xmlhttprequests, pay attention to setting timeout

XMLHttpRequests at execution time, when there is no response for a long time (such as a network problem, etc.), the connection should be aborted and the work can be done through settimeout ():

var xhr = new XMLHttpRequest ();

Xhr.onreadystatechange = function () {

if (this.readystate = = 4) {

Cleartimeout (timeout);

Do something with response data

}

}

var timeout = setTimeout (function () {

Xhr.abort (); Call Error Callback

}, 60*1000/* Timeout after a minute */);

Xhr.open (' GET ', url, true);

Xhr.send ();

It is also important to note that you should not initiate multiple xmlhttprequests requests at the same time.

42. Processing WebSocket Timeout

Typically, after a websocket connection is created, if there is no activity within 30 seconds, the server will time out the connection, and the firewall can time out the connection with no active connections for the unit cycle.

To prevent this from happening, you can send an empty message to the server at a certain time. You can implement this requirement by using these two functions, one for keeping the connection active and the other for ending the state.

var timerid = 0;

function keepAlive () {

var timeout = 15000;

if (websocket.readystate = = Websocket.open) {

Websocket.send (");

}

Timerid = setTimeout (keepAlive, timeout);

}

function cancelkeepalive () {

if (Timerid) {

Canceltimeout (Timerid);

}

}

The keepAlive () function can be placed on the last side of the OnOpen () method of the WebSocket connection, and cancelkeepalive () is placed at the very end of the OnClose () method.

43, time note primitive operators faster than function calls, using VANILLAJS

For example, generally don't do this:

var min = Math.min (A, b);

A.push (v);

This can be replaced by:

var min = a < b? A:B;

A[a.length] = v;

44. Pay attention to code structure during development, check and compress JavaScript code before go online

Don't forget to use a code beautification tool when writing code. Use JSLint (a grammar checker) and compress the code (for example, using jsmin) before you go online. Note: Code compression is now generally recommended UGLIFYJS (HTTPS://GITHUB.COM/MISHOO/UGLIFYJS2)

45, JavaScript is profound, there are some good learning resources

Code Academy Resources: Http://www.codecademy.com/tracks/javascript

Eloquent javascript:http://eloquentjavascript.net/written by Marjin Haverbekex

The advanced javascript:http://ejohn.org/apps/learn/written by John Resig

45 kinds of JavaScript skills Daquan

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.