JavaScript Tips 45 Strokes

Source: Internet
Author: User

Original: Useful JavaScript Tips, Tricks and best practices
Saad Mousliki

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.

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! =.

1 [] = = =//is FALSE2 [ten] = =//is true3 ' = = +//is true4 ' = = =//are false5 [] = = 0//is true6 [] = = = 0//is false7 ' = = False//is true but true = = "A" is false8 ' = = = = = 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

1 function person (firstName, lastName) {2     this.firstname = firstname;3     this.lastname = lastname;4}5 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; Return "Object" arr instanceof Array//Truearr.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:

1 (function () {2     //code placed here will automatically execute 3}); 4 5 (function (A, b) {6     var result = A+b;7     return result;8}) (10,20)


8. Get members randomly from the array
1 var items = [548, ' a ', 2, 5478, ' foo ', 8852,, ' Doe ', 2145, 119];

2 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

12345 functiongenerateRandomAlphaNum(len) {    var rdmString = "";    for( ; rdmString.length < len; rdmString += Math.random().toString(36).substr(2));    returnrdmString.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

1 var array1 = ["foo", {name "Joe"}, -2458];2 var array2 = ["Doe", 555, 100];3 Array.prototype.push.apply (Array1, ARRAY2); 4/* Array1 value is [N, "foo", {name "Joe"}, -2458, "Doe", 555, 100] */

15. Object conversions to arrays
var Argarray = Array.prototype.slice.call (arguments);

16, verify whether the number

123 functionisNumber(n){    return!isNaN(parseFloat(n)) && isFinite(n);}

  

17. Verify that it is an array

1 function IsArray (obj) {2     return Object.prototype.toString.call (obj) = = = ' [Object Array] '; 3}

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.

1 var myframe = document.createelement (' iframe '); 2 document.body.appendChild (MyFrame); 3 var myArray = window.frames[ WINDOW.FRAMES.LENGTH-1]. array;4 var arr = new MyArray (a,b,10); [a,b,10] 5//MyArray The constructor has been lost, the result of instanceof will not be normal 6//The constructor is 7 arr instanceof Array that cannot be shared across the frame; False

18. Get the maximum and minimum values in the array

1 var numbers = [5, 458, 120,-215, 228, 400, 122205,-85411]; 2 var maxinnumbers = Math.max.apply (Math, numbers); 3 var mininnumbers = Math.min.apply (Math, numbers);

19. Empty the array

1 var myArray = [12, 222, 1000]; 2 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:

1 var items = [548, ' a ', 2, 5478, ' foo ', 8852,, ' Doe ', 2154, 119];  2 items.length; Return  3 Delete items[3];//return True  4 items.length;//Return 5/  * items result for [548, "a", unde  FINEDX1, 5478, "foo", 8852, Undefinedx1, "Doe", 2154, 119] */6//instead: 7 var items = [, 548, ' a ', 2, 5478, ' foo ', 8852,, ' Doe ', 2154, 119];  8 items.length; Return  9 Items.splice (3,1), items.length;//Return  */* Items results for [, 548, "a", 5478, "foo", 8852, UN DEFINEDX1, "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:

1 var myArray = [12, 222, 1000, 124, 98, 10]; 2 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.

1 myarray.length = 10; The new array length is 2 myarray[myarray.length-1]; Undefined

22. Use logic and or in conditions

1 var foo = 10; 2 foo = && dosomething (); Is the same thing as if (foo = =) dosomething (); 3 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.

1 function dosomething (arg1) {2     arg1 = Arg1 | |;//ARG1 would have ten as a default value if it ' s not already set3}

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

1 var squares = [1,2,3,4].map (function (val) {2     return val * val; 3}); 4//Squares'll be is equal to [1, 4, 9, 16]

24. Keep the specified number of decimal digits

1 var num =2.443242342;2 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

1 0.1 + 0.2 = = = 0.3//is false 2 9007199254740992 + 1//are equal to 90071992547409923 9007199254740992 + 2//is equal T o 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.

1 for (var name in object) {2   if (Object.hasownproperty (name)) {3     //does something with Name4   } 5}

27. Comma operator

1 var a = 0; 2 var b = (a++, 99); 3 Console.log (a); A'll is equal to 1 4 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.

1 var navright = document.queryselector (' #right '); 2 var navleft = document.queryselector (' #left '); 3 var navup = document.queryselector (' #up '); 4 var navdown = document.queryselector (' #down ');

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

1 isfinite (0/0); False2 isfinite ("foo"); False3 isfinite ("10"); True4 Isfinite (10); True5 isfinite (undefined); False6 isfinite (); False7 isfinite (NULL); True, this is when special attention is paid to

30. Avoid using negative numbers in the array to index

1 var numbersarray = [1,2,3,4,5];2 var from = Numbersarray.indexof ("foo"); From is equal to-13 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

1 var person = {name: ' Saad ', age:26, department: {id:15, Name: "R/r"}};2 var Stringfromperson = json.stringify (person); 3//Stringfromperson The result is "{" "Name": "Saad", "age": +, "department": {"ID": [], "name": "R/r}}" */4 var personfromstring = Json.parse (Stringfromperson); 5/* personfromstring the same value 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.

1 var func1 = new Function (Functioncode), 2 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

1 var sum = 0; 2 for (var i in arraynumbers) {3     sum + = Arraynumbers[i]; 4}

But:

1 var sum = 0; 2 for (var i = 0, len = arraynumbers.length; i < Len; i++) {3     sum + = Arraynumbers[i]; 4}

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:

1 function getcategory (age) {   2     var category = "";   3     switch (true) {   4 case         IsNaN [age]:   5             category = "   not a Age"; 6 break             ;   7 Case         (age >=):   8             category = "old";   9 Break             ;  Ten case         (age <=):             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:

1 function Clone (object) {  2     function Oneshotconstructor () {}; 3     Oneshotconstructor.prototype = object;  4     return new Oneshotconstructor (); 5} 6 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.

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      }} and 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 ():

1 var xhr = new XMLHttpRequest ();  2 Xhr.onreadystatechange = function () {   3     if (this.readystate = = 4) {   4         cleartimeout (timeout);   5         //Do something with response data  6     }   7}   8 var timeout = setTimeout (function () {   9     xh R.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.

1 var timerid = 0;  2 function keepAlive () {  3     var timeout = 15000;   4     if (websocket.readystate = = Websocket.open) {   5         websocket.send (");   6     }   7     Timerid = setTimeout (keepAlive, timeout);   8}   9 function cancelkeepalive () {  ten     if (Timerid) {  one         canceltimeout (Timerid);  The  }14 keepAlive () function can be placed at the end of the WebSocket connected OnOpen () method, and Cancelkeepalive () 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
You can use tools such as JSLint or jsmin to examine and compress your code.

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

JavaScript tips 45 Strokes (RPM)

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.