Share the classic JavaScript development tips _ javascript tips-js tutorials

Source: Internet
Author: User
This article shares more than 40 typical JavaScript development skills with you. I believe that reading this article will greatly help you develop javascript, if you are interested, refer to the typical JavaScript development skills to share with you:

1. When assigning values to variables for the first time, you must use the var keyword.

Variables are directly assigned without declaration. By default, they are used as a new global variable. Avoid using global variables whenever possible.
2. Use = replace =

= And! = The operator will automatically convert the data type as needed. But = and! = No, they compare values and data types at the same time, which also makes them equal to = and! = Fast.
[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 results of underfined, null, 0, false, NaN, and null strings are all false.

4. Use a semicolon at the end of the line

In practice, it is best to use a semicolon. If you forget to write it, The JavaScript interpreter will be automatically added in most cases.

5. Use the object constructor

function Person(firstName, lastName){ this.firstName = firstName; this.lastName = lastName;}var Saad = new Person("Saad", "Mousliki");

6. Use typeof, instanceof, and contructor with caution.

  • Typeof: JavaScript unary operator, used to return the original type of the variable in the form of a string. Note that typeof null also returns the object. Most object types (Array, time Date, etc) will also return the object
  • Contructor: Internal prototype attribute, which can be rewritten through code
  • Instanceof: JavaScript operator, which is searched by the constructor in the prototype chain. If it is found, true is returned. Otherwise, false is returned.

Var arr = ["a", "B", "c"]; typeof arr; // return "object" arr instanceof Array // truearr. constructor (); // []

7. Use self-called Functions

A Function is automatically executed after it is created. It is generally called a Self-Invoked Anonymous Function or an Immediately Invoked Function Expression ). The format is as follows:

(Function () {// The Code put here will be automatically executed}) (); (function (a, B) {var result = a + B; return result ;}) (10, 20)

8. Randomly retrieve members from the array

var items = [12, 548 , 'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' , 2145 , 119];var randomItem = items[Math.floor(Math.random() * items.length)];

9. Obtain random numbers within a specified range

This function is especially useful when generating false data for testing, such as the number of salaries within a specified range.

The Code is as follows:

Var x = Math. floor (Math. random () * (max-min + 1) + min;


10. Generate a number array from 0 to the specified value

var numbersArray = [] , max = 100;for( var i=1; numbersArray.push(i++) < max;); // numbers = [1,2,3 ... 100]

11. generate random letters and numbers

function generateRandomAlphaNum(len) { var rdmString = ""; for( ; rdmString.length < len; rdmString += Math.random().toString(36).substr(2)); return rdmString.substr(0, len);}

12. disrupt the order of number Arrays

Var numbers = [5,458,120,-215,228,400,122 205,-85411]; numbers = numbers. sort (function () {return Math. random ()-0.5});/* The numbers array will be similar to [120, 5,228,-215,400,458,-85411,122] */

Here we use the array sorting function built in JavaScript. A better way is to use special code (such as the Fisher-Yates algorithm). For details, see the discussion on StackOverFlow.
13. Remove spaces from strings

Java, C #, PHP, and other languages all implement special string space-removing functions, but JavaScript does not. You can use the following codeString objectFunction 1Trim Function:
String. prototype. trim = function () {return this. replace (/^ \ s + | \ s + $/g ,"");};
The new JavaScript Engine is available.Trim ()Native Implementation.
14. appending between Arrays

Var array1 = [12, "foo", {name "Joe"},-2458]; var array2 = ["Doe", 555,100]; Array. prototype. push. apply (array1, array2);/* the value of array1 is [12, "foo", {name "Joe"},-2458, "Doe", 555,100] */

15. convert an object to an array

The Code is as follows:

Var argArray = Array. prototype. slice. call (arguments );


16. Verify if it is a number

function isNumber(n){ return !isNaN(parseFloat(n)) && isFinite(n);}

17. Verify whether it is an array

function isArray(obj){ return Object.prototype.toString.call(obj) === '[object Array]' ;}

However, ifToString ()If the method is overwritten, it will not work. You can also use the following method:

The Code is as follows:

Array. isArray (obj); // its a new Array method


If frame is not used in the browser, you can also use instanceof. However, if the context is too complex, errors may occur.

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); // The constructor of [a, B, 10] // myArray has been lost, the instanceof result will be abnormal // The constructor cannot share the arr instanceof Array across frames; // false

18. obtain 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);

For details, refer to this article: How does JavaScript obtain the maximum and minimum values of arrays?

19. Clear the Array

var myArray = [12 , 222 , 1000 ]; myArray.length = 0; // myArray will be equal to [].

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

If you directly use the array elementDeleteBut the elements are not deleted.Undefined. Array Element deletion should be usedSplice.
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/* The items result is [12,548, "a", undefined × 1, 5478, "foo", 8852, undefined × 1, "Doe ", 2154,119] */

But 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 result: [12,548, "a", 5478, "foo", 8852, undefined × 1, "Doe", 2154,119]

Delete can be used to delete attributes of an object.
21. Use the length attribute to truncate the array.

In the previous exampleLengthAttribute to clear the array. 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 increase the length attribute, the length value of the array will increase, and undefined will be used to fill the new element. Length is a writable attribute.

myArray.length = 10; // the new array length is 10 myArray[myArray.length - 1] ; // undefined

22. Use logic in conditions and

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();

Logical or can also be used to set default values, such as the default values of 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 cycle the data.

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

24. Retain the specified decimal places

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. Floating Point computing problems

0.1 + 0.2 = 0.3 // is false
9007199254740992 + 1 // is equal to 9007199254740992
9007199254740992 + 2 // is equal to 9007199254740994

Why? Because 0.1 + 0.2 equals 0.30000000000000004. JavaScript numbers follow the IEEE 754 standard and are represented by 64-bit floating point decimals. For details, see how the numbers in JavaScript are encoded.
You can solve this problem by using toFixed () and toPrecision.
26. Check the object attributes through the for-in Loop

The following usage prevents objects from entering the prototype attribute during iteration.

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 calculation and query

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 input isFinite () parameters in advance

IsFinite (0/0); // falseisFinite ("foo"); // falseisFinite ("10"); // trueisFinite (10); // trueisFinite (undefined ); // falseisFinite (); // falseisFinite (null); // true, which deserves special attention.

30. Avoid using negative numbers in the array for indexing.

var numbersArray = [1,2,3,4,5]; var from = numbersArray.indexOf("foo") ; // from is equal to -1 numbersArray.splice(from,2); // will return [5]

NoteSpliceThe index parameter is not a negative number. When it is a negative number, the elements are deleted from the end of the array.
31. Use JSON for serialization and deserialization

Var person = {name: 'saad', age: 26, department: {ID: 15, name: "R & D" }}; var stringFromPerson = JSON. stringify (person);/* stringFromPerson returns "{" name ":" Saad "," age ": 26," department ": {" ID ": 15, "name": "R & D"} "*/var personFromString = JSON. parse (stringFromPerson);/* the value of personFromString is the same as that of the person object */

32. Do not use eval () or function Constructor

Eval ()And Function consturctor (Function consturctor) have a high overhead. Each call, the JavaScript engine must convert the source code to executable code.

var func1 = new Function(functionCode);var func2 = eval(functionCode);

33. Avoid using ()

With () can be used to add variables to the global scope. Therefore, if there are other variables with the same name, it is easy to confuse and the second value will be 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 the I and len variables are initialized only once in the first declaration of the for loop, which is faster than the following statement:
For (var I = 0; I <arrayNumbers. length; I ++)
35. Use a function instead of a string when it is passed to setInterval () and setTimeout ()

If it is passed to a string of setTimeout () and setInterval (), they will convert it in a way similar to eval, which must be slower, so do not use:

setInterval('doSomethingPeriodically()', 1000); setTimeout('doSomethingAfterFiveSeconds()', 5000);

Instead, use:

setInterval(doSomethingPeriodically, 1000); setTimeout(doSomethingAfterFiveSeconds, 5000);

36. Use switch/case to replace a large stack of if/else

When judging that there are more than two branches, it is faster to use switch/case, and it is more elegant and more conducive to the Code Organization. Of course, if there are more than 10 branches, do not use switch/case.
37. use numeric intervals in switch/case

In fact, the case condition in switch/case can also be written as follows:

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" is returned"

38. Use an object as the prototype of the object

In this way, you can specify an object as a parameter to create a new object based on this prototype:

function clone(object) {  function OneShotConstructor(){};  OneShotConstructor.prototype = object;  return new OneShotConstructor(); } clone(Array).prototype ; // []

39. HTML field conversion functions

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 part in try-catch-finally assigns an exception to a variable during execution, which is constructed into a new variable in the runtime scope.
Avoid:

Var object = ['foo', 'bar'], I; for (I = 0, len = object. length; I
 
  

However, we should:

Var object = ['foo', 'bar'], I; try {for (I = 0, len = object. length; I
   
    

41. set timeout when using XMLHttpRequests

When XMLHttpRequests is executed, when there is no response for a long time (such as a network problem), the connection should be aborted.SetTimeout ()To complete this task:

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();

At the same time, you must note that do not initiate multiple XMLHttpRequests requests at the same time.
42. Processing WebSocket timeout

Generally, after a WebSocket connection is created, if there is no activity within 30 seconds, the server will process the connection timeout, And the firewall can also process the timeout for connections that are not active in a unit cycle.
To prevent this situation, you can send an empty message to the server at intervals. The following two functions can be used to achieve this requirement. One is used to maintain the active state of the connection, and the other is used to end 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 ()Functions can be stored in WebSocket connectionsOnOpen ()At the end of the method,CancelKeepAlive ()Put inOnClose ()The end of the method.

The above are the javascript development skills shared for you and hope to help you learn them.

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.