JavaScript-45 classic tricks and attention points

Source: Internet
Author: User
Tags array length setinterval

1. Be sure to use the first time you assign a value to a variable var / let / constKey words

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 = = = to replace = =

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

[10] === 10    // is false[10]  == 10    // is true'10' == 10     // is true'10' === 10    // is false[]   == 0     // is true[] ===  0     // is false'' == false   // is true but true == "a" is false'' === false  // is false
3. The logical result of underfined, NULL, 0, False, NaN, and empty string is false4. It's a good habit to use semicolons 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
    • typeof: JavaScript unary operator, used to return the original type of a variable as a string, note that typeof null also returns an object, and most object types (array arrays, time date, and so on) also return an object
    • contructor: Internal prototype properties, which can be overridden by code
    • instanceof: javascript operator, search in constructor in prototype chain, return True if found, false otherwise

      var arr = ["a", "b", "c"];typeof arr;   // 返回 "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(){    // 置于此处的代码将自动执行})();  (function(a,b){    var result = a+b;    return result;})(10,20)
8. Getting members randomly from an array
var items = [12, 548 , 'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' , 2145 , 119];var  randomItem = items[Math.floor(Math.random() * items.length)];
9. Get the random number in the 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; i < max ; i++){    numbersArray.push(i);};  // numbers = [1,2,3 ... 100]
11. Generate a random alphanumeric string
function generateRandomAlphaNum(len) {    var rdmString = "";    for( ; rdmString.length < len; rdmString  += Math.random().toString(36).substr(2));    return  rdmString.substr(0, len);}
12. Scrambling the sequence of numeric arrays
var numbers = [5, 458 , 120 , -215 , 228 , 400 , 122205, -85411];numbers = numbers.sort(function(){ return Math.random() - 0.5});/* numbers 数组将类似于 [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 trim() native implementation.

14. Append between arrays
var array1 = [12 , "foo" , {name "Joe"} , -2458];var array2 = ["Doe" , 555 , 100];Array.prototype.push.apply(array1, array2);/* array1 值为  [12 , "foo" , {name "Joe"} , -2458 , "Doe" , 555 , 100] */
15. Object conversions to arrays
///方式1var arr1 = Array.prototype.slice.call(arguments);//方式2var arr2 = []for (var i in object) {    arr.push(object[i]); //属性    //arr.push(object[i]); //值}//方式3let arr3 = [].slice.call(arrayLike);let arr4 = Array.from(arrayLike);
16. Verify that it is a digital
function isNumber(n){    return !isNaN(parseFloat(n)) && isFinite(n);}
17. Verify that the array
    1. Mode 1:
      function IsArray (obj) {
      return Object.prototype.toString.call (obj) = = = ' [Object Array] ';
      }

    2. Mode 2:

      ES6 Syntax:

      Array.isArray(param);
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. Emptying the array
var myArray = [12 , 222 , 1000 ];  myArray.length = 0; // myArray will be equal to [].
20. Do not directly from the array DeleteOr RemoveElements

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 = [12, 548 ,'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' ,2154 , 119 ]; items.length; // return 11 delete items[3]; // return true items.length; // return 11 /* items 结果为 [12, 548, "a", undefined × 1, 5478, "foo", 8852, undefined × 1, "Doe", 2154, 119] */

Instead, you should:

var items = [12, 548 ,'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' ,2154 , 119 ]; items.length; // return 11 items.splice(3,1) ; items.length; // return 10 /* items 结果为 [12, 548, "a", 5478, "foo", 8852, undefined × 1, "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 uses the length property to empty the array, and it can also be used to truncate the array:

var myArray = [12 , 222 , 1000 , 124 , 98 , 10 ];  myArray.length = 4; // myArray will be 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 with or in conditions
var foo = 10;  foo == 10 && doSomething(); // is the same thing as if (foo == 10) 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 will have 10 as a default value if it’s not already set}
23. Make the map () function method on the data loop
var squares = [1,2,3,4].map(function (val) {      return val * val;  }); // squares will be equal to [1, 4, 9, 16]
24. Keep the specified number of decimal digits
var num =2.443242342;num = num.toFixed(4);  // num will be equal to 2.4432

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

25. Problems with floating-point calculations
0.1 + 0.2 === 0.3 // is false 9007199254740992 + 1 // is equal to 90071992547409929007199254740992 + 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.

This problem can be solved by using toFixed() and toPrecision() .

26. Checking the properties of an 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 will be equal to 1 console.log(b);  // b is equal to 99
28. Temporary storage of 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(10);   // trueisFinite(undefined);  // falseisFinite();   // falseisFinite(null);  // true,这点当特别注意
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); // will 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. Using JSON to serialize and deserialize
var person = {name :'Saad', age : 26, department : {ID : 15, name : "R&D"} };var stringFromPerson = JSON.stringify(person);/* stringFromPerson 结果为 "{"name":"Saad","age":26,"department":{"ID":15,"name":"R&D"}}"   */var personFromString = JSON.parse(stringFromPerson);/* personFromString 的值与 person 对象相同  */

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 for arrays

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 number 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 an age";              break;          case (age >= 50):              category = "Old";              break;          case (age <= 20):              category = "Baby";              break;          default:              category = "Young";              break;      };      return category;  }  getCategory(5);  // 将返回 "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 that 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 that throws an exception     } } catch (e) {       // handle exception  }
41. Note set timeout when using xmlhttprequests

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. Handling Timeouts for WebSocket

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 are faster than function calls, 2 use 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 Eslint (a grammar checker tool). Note: Code compression is now generally recommended UGLIFYJS (HTTPS://GITHUB.COM/MISHOO/UGLIFYJS2)

JavaScript is profound, there are some good learning resources here.
    1. Code Academy Resources
    2. Eloquent JavaScript written by Marjin Haverbekex
    3. Advanced JavaScript written by John Resig

JavaScript-45 classic tricks and attention points

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.