JavaScript is a world-class programming language that can be used for web development, mobile application development (PhoneGap, Appcelerator), server-side development (and Wakanda), etc. JavaScript is also the first language for many newbies to enter the programming world. It can be used to display simple prompt boxes in the browser, or to control the robot through nodebot or noderuino. Developers who can write well-structured and efficient JavaScript code are now the most sought after people in the recruitment market
1. Be sure to use the var keyword when assigning a value to a variable for the first time.
If a variable is not declared and is directly assigned to the value, it will be used as a new global variable by default. Try to avoid using global variables.
2. Use ===Replace ==
The == and != operators will automatically convert the data type if needed. But === and !== will not, they will compare values and data types at the same time, which also makes them faster than == and !=.
[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 empty strings are all false
4. Use semicolons at the end of the line
In practice, it is best to use semicolons. It is okay to forget to write them. In most cases, the JavaScript interpreter will be automatically added. For why you want to use a semicolon, you can refer to the truth about semicolons in the article JavaScript (/javascript-semicolons)。
5. Use object constructor
function Person(firstName, lastName){ = firstName; = lastName; } var Saad = new Person("Saad", "Mousliki");
6. Be careful to use typeof, instanceof and constructor
- typeof: JavaScript unary operator, used to return the original type of a variable in the form of a string. Note that typeof null will also return object, and most object types (array, time Date, etc.) will also return object.
- constructor: internal prototype properties, which can be rewritten through code
- instanceof: JavaScript operator, will search in the constructor in the prototype chain, return true if found, otherwise return false if false.
var arr = ["a", "b", "c"]; typeof arr; // Return to "object"arr instanceof Array // true (); //[]
7. Use self-call functions
Functions are automatically executed directly after creation, which is usually called self-Invoked Anonymous Function or direct call function expressions (Immediately Invoked Function Expression). The format is as follows:
(function(){ // The code placed here will be automatically executed})(); (function(a,b){ var result = a+b; return result; })(10,20)
8. Randomly obtain members from the array
var items = [12, 548 , 'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' , 2145 , 119]; var randomItem = items[(() * )];
9. Get random numbers within the specified range
This function is particularly numeric when generating false data for testing, such as the number of wages within a specified range.
var x = (() * (max - min + 1)) + min;
10. Generate an array of numbers from 0 to specified values
var numbersArray = [] , max = 100; for( var i=1; (i++) < max;); // numbers = [1,2,3 ... 100]
11. Generate random alphanumeric strings
function generateRandomAlphaNum(len) { var rdmString = ""; for( ; < len; rdmString += ().toString(36).substr(2)); return (0, len); }
12. Disrupt the order of arrays of numbers
var numbers = [5, 458 , 120 , -215 , 228 , 400 , 122205, -85411]; numbers = (function(){ return () - 0.5}); /* numbers array will be similar to [120, 5, 228, -215, 400, 458, -85411, 122205] */
Here we use the built-in array sorting function of JavaScript. A better way is to implement it with special code (such as the Fisher-Yates algorithm). You can refer to this discussion on *.
13. Remove spaces from strings
= function(){return (/^\s+|\s+$/g, "");};
The new JavaScript engine already has a native implementation of trim().
14. Adding between arrays
var array1 = [12 , "foo" , {name "Joe"} , -2458]; var array2 = ["Doe" , 555 , 100]; (array1, array2); /* array1 value is [12 , "foo" , {name "Joe"} , -2458 , "Doe" , 555 , 100] */
15. Convert objects into arrays
var argArray = (arguments);
16. Verify whether it is a number
function isNumber(n){ return !isNaN(parseFloat(n)) && isFinite(n); }
17. Verify whether it is an array
function isArray(obj){ return (obj) === '[object Array]' ; }
But if the toString() method is rewritten, it won't work. You can also use the following method:
(obj); // its a new Array method
If you do not use frame in your browser, you can also use instanceof, but if the context is too complex, you may also make an error.
var myFrame = ('iframe'); (myFrame); var myArray = [-1].Array; var arr = new myArray(a,b,10); // [a,b,10] // myArray's constructor has been lost, the result of instanceof will be abnormal// Constructors cannot be shared across framesarr instanceof Array; // false
18. Get the maximum and minimum values in the array
var numbers = [5, 458 , 120 , -215 , 228 , 400 , 122205, -85411]; var maxInNumbers = (Math, numbers); var minInNumbers = (Math, numbers);
19. Clear the array
var myArray = [12 , 222 , 1000 ]; = 0; // myArray will be equal to [].
20. Do not delete or remove elements directly from the array
If you use delete directly on array elements, it is not actually deleted, but just set the element as undefined. Splice should be used for array element deletion.
Don't:
var items = [12, 548 ,'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' ,2154 , 119 ]; ; // return 11 delete items[3]; // return true ; // return 11 /* items result is [12, 548, "a", undefined × 1, 5478, "foo", 8852, undefined × 1, "Doe", 2154, 119] */
As for:
var items = [12, 548 ,'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' ,2154 , 119 ]; ; // return 11 (3,1) ; ; // return 10 /* items The result is [12, 548, "a", 5478, "foo", 8852, undefined × 1, "Doe", 2154, 119]
You can use delete when deleting an object's properties.
21. Use the length attribute to truncate the array
In the previous example, use the length attribute to clear the array, and you can also use it to truncate the array:
var myArray = [12 , 222 , 1000 , 124 , 98 , 10 ]; = 4; // myArray will be equal to [12 , 222 , 1000 , 124].
At the same time, if the length attribute is increased, the length value of the array will increase, and undefined will be used as a new element to fill. length is a writable property.
= 10; // the new array length is 10 myArray[ - 1] ; // undefined
22. Use logic and 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();
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 loop the data
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 places
var num =2.443242342; num = (4); // num will be equal to 2.4432
Note that toFixec() returns a string, not a number.
25. Problems of floating point calculation
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 is equal to 0.3000000000000000000004. JavaScript numbers are constructed according to the IEEE 754 standard and are represented internally by 64-bit floating point decimals. For details, please refer to how the numbers in JavaScript are encoded.
This problem can be solved by using toFixed() and toPrecision().
26. Check the object's properties through the for-in loop
The following usage can prevent it from entering the prototype properties of the object during iteration.
for (var name in object) { if ((name)) { // do something with name } }
27. Comma operator
var a = 0; var b = ( a++, 99 ); (a); // a will be equal to 1 (b); // b is equal to 99
28. Temporary storage of variables used for calculation and query
In jQuery selector, the entire DOM element can be temporarily stored.
var navright = ('#right'); var navleft = ('#left'); var navup = ('#up'); var navdown = ('#down');
29. Check the parameters passed in isFinite() in advance
isFinite(0/0) ; // false isFinite("foo"); // false isFinite("10"); // true isFinite(10); // true isFinite(undefined); // false isFinite(); // false isFinite(null); // true,Pay special attention to this
30. Avoid using negative numbers as indexing in arrays
var numbersArray = [1,2,3,4,5]; var from = ("foo") ; // from is equal to -1 (from,2); // will return [5]
Note that the index parameter passed to splice is not negative. When it is a negative number, the element will be deleted from the end of the array.
31. Use JSON to serialize and deserialize
var person = {name :'Saad', age : 26, department : {ID : 15, name : "R&D"} }; var stringFromPerson = (person); /* stringFromPerson result is "{"name":"Saad","age":26,"department":{"ID":15,"name":"R&D"}}" */ var personFromString = (stringFromPerson); /* The value of personFromString is the same as that of person object */
32. Do not use eval() or function constructor
The overhead of eval() and function constructors is high. Each time they are called, the JavaScript engine needs to convert the source code into executable code.
var func1 = new Function(functionCode); var func2 = eval(functionCode);
33. Avoid using with()
Use with() to add variables to the global scope. Therefore, if there are other variables with the same name, it is easy to be confused, and the value will be overwritten.
34. Do not use for-in for arrays
avoid:
var sum = 0; for (var i in arrayNumbers) { sum += arrayNumbers[i]; }
Instead:
var sum = 0; for (var i = 0, len = ; i < len; i++) { sum += arrayNumbers[i]; }
Another advantage is that the two variables i and len are in the first declaration of the for loop, and both will be initialized only once, which is faster than the following writing method:
for (var i = 0; i < ; i++)
35. Use functions instead of strings when passing to setInterval() and setTimeout()
If you pass a string to setTimeout() and setInterval(), they will convert in a similar way to eval, which will definitely be slower, so don't 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
When judging that there are more than two branches, use switch/case is faster, and more elegant, and more conducive to the organization of code. Of course, if there are more than 10 branches, do not use switch/case.
37. Use digital intervals in switch/case
In fact, the case conditions 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); // Will return "Baby"
38. Use objects as prototypes
In this way, you can create a new object with this prototype by giving the object as a parameter:
function clone(object) { function OneShotConstructor(){}; = object; return new OneShotConstructor(); } clone(Array).prototype ; // []
39. HTML field conversion function
function escapeHTML(text) { var replacements= {"<": "<", ">": ">","&": "&", "\"": """}; return (/[<>&"]/g, function(character) { return replacements[character]; }); }
40. Do not use try-catch-finally inside the loop
The catch part in try-catch-finally will assign exceptions to a variable when executed, and this variable will be constructed into a new variable within the runtime scope.
Don't:
var object = ['foo', 'bar'], i; for (i = 0, len = ; i <len; i++) { try { // do something that throws an exception } catch (e) { // handle exception } }
Instead:
var object = ['foo', 'bar'], i; try { for (i = 0, len = ; i <len; i++) { // do something that throws an exception } } catch (e) { // handle exception }
41. Pay attention to setting timeout when using XMLHttpRequests
When XMLHttpRequests is executed, when there is no response for a long time (such as network problems, etc.), the connection should be aborted. This work can be done by setTimeout():
var xhr = new XMLHttpRequest (); = function () { if ( == 4) { clearTimeout(timeout); // do something with response data } } var timeout = setTimeout( function () { (); // call error callback }, 60*1000 /* timeout after a minute */ ); ('GET', url, true); ();
At the same time, it should be noted that multiple XMLHttpRequests requests should not be initiated at the same time.
42. Handle the timeout of WebSocket
Generally speaking, after the WebSocket connection is created, if there is no activity within 30 seconds, the server will time out the connection, and the firewall can also time out the connection that is not active in a unit cycle.
In order to prevent this from happening, an empty message can be sent to the server every certain time. This requirement can be achieved through the following two functions, one for keeping the connection active and the other specifically for ending this state.
var timerID = 0; function keepAlive() { var timeout = 15000; if ( == ) { (''); } timerId = setTimeout(keepAlive, timeout); } function cancelKeepAlive() { if (timerId) { cancelTimeout(timerId); } }
The keepAlive() function can be placed at the end of the onOpen() method of the WebSocket connection, and cancelKeepAlive() can be placed at the end of the onClose() method.
43. Pay attention to the time and the original operator is faster than the function call. Use VanillaJS
For example, generally not like this:
var min = (a,b); (v);
This can be used instead:
var min = a < b ? a : b; A[] = v;
44. Pay attention to the code structure during development, check and compress JavaScript code before going online
You can use tools such as JSLint or JSMin to check and compress the code.
The above is all the content of this article. I hope that the content of this article will help you study or work. I also hope to support me more!