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[10]  = =//is    true ' = =/     /is true ' = = = =//is    false []   = = 0
   //is true [] = =  0     //is false "= = False   //is true but true = =" A "is false" = = = = False  //is FAL Se
3, underfined, NULL, 0, False, NaN, the logical result of the empty string is False 4, the end of the line uses a semicolon

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;   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:

(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.ran Dom () * 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, -215, 228, 122205, -85411];numbers = Numbers.sort (function () {return math.random ()- 0.5});/* numbers array will resemble [5, 228, -215, +, 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 is  [ -2458, "foo", {name "Joe"},, "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 ');d ocument.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//The constructor is an arr instanceof Array that cannot be shared across the frame;//False
18. Get the maximum and minimum values in the array
var  = [5, 458, -215, 228, Numbers, 122205, -85411]; var maxinnumbers = Math.max.apply (Math, numbers); VA R mininnumbers = Math.min.apply (Math, numbers);
19. Empty the array
var MyArray = [N, 222, +];  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 one delete items[3]; return True items.length; Return one/* 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 one items.splice (3,1); Items.length; return */* 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 = [N, 222, +, 124, 98, ten];  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 ten myarray[myarray.length-1]; Undefined
22. Use logic and or in conditions
var foo = ten;  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 | |;//ARG1 would have 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 is 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//are equal to 90071992547409929007199254740992 + 2//are equal to 9007 199254740994

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)) {         //does 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); Falseisfinite ("foo"); Falseisfinite ("10"); Trueisfinite (ten);   Trueisfinite (undefined);  Falseisfinite ();   Falseisfinite (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 & R"}};var Stringfromperson = Json.stringify (per son);/* Stringfromperson result is "{" 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 () ', +);  SetTimeout (' Dosomethingafterfiveseconds () ', 5000);

Instead, use:

SetInterval (dosomethingperiodically, +);  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:              category = ' not ' age ';              break;          Case (age >=):              category = ' old ';              break;          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:

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.