(turn) JavaScript 44 strokes of kinky tricks

Source: Internet
Author: User

1. Be sure to use the var keyword when assigning a value to 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, the use of === replacement ==

==and != operators will automatically convert the data type if needed. But === and !== not, they compare values and data types at the same time, which makes them == faster and != quicker.

[[] = = =    //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 False
   
3, underfined , null , 0, False, NaN, empty string logical result is false4. 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, careful use typeof , instanceof and contructor
    • typeof: The JavaScript unary operator, which returns the original type of the variable as a string, noting that typeof null it also returns object , most of the object types (array, date, and so on) will also returnobject
    • contructor: Internal prototype properties, which can be overridden by code
    • instanceof: The javascript operator, which searches the constructor in the prototype chain, returns if found, true or returnsfalse
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 one in JavaScript, and you can use the following code to function a function for String an object trim :

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

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

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 it 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 directly from the array delete or remove element

If the array element is used directly, it is delete not deleted, but the element is placed in order undefined . array element deletions should be used 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]

can be used when deleting properties of an object delete .

21. length truncating an array with attributes

The previous example uses the length property to empty the array, and it can also be 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 length value of the array will increase and will be used undefined as a new element to populate. lengthis 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() the function method to the data circulation
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 the toFixec() returned string is 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.

This problem can be solved 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 incoming isFinite() parameters 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-1numbersarray.splice (from,2);    would return [5]

Note that splice the passed index parameter 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 constructors

eval()and the function constructor ( Function consturctor) are expensive, and each invocation, the JavaScript engine converts the source code into executable code.

var func1 = new Function (functioncode), var func2 = eval (functioncode);
33. Avoid using with()

with()variables can be added to the global scope, so if there are other variables with 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 for first declaration of the Loop, and the two are initialized only once, which is faster than the following:

for (var i = 0; i < arraynumbers.length; i++)
35. setInterval() setTimeout() use functions instead of strings when passed to and

If passed setTimeout() and setInterval() a string, they will be converted in a similar eval way, 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 if/else of

When judging more than two branches switch/case to use faster, but also more elegant, more conducive to the organization of code, of course, if there are more than 10 branches, do not use switch/case .

37, in the switch/case use of digital range

In fact, switch/case in the case conditions, you can also write:

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= {"<": "&lt;", ">": "&gt;", "&": "&amp;", "\" ":" & Amp;quot; "};                          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 {          //does something that throws an exception     }      CATC H (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 when executing, when there is no response for a long time (such as a network problem, etc.), should abort the connection, you can setTimeout() complete the work:

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 ER ROR 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);      }  }

keepAlive()The function can be placed at the end of the method of the WebSocket connection onOpen() , cancelKeepAlive() at the very bottom 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.

(turn) JavaScript 44 strokes of kinky tricks

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.