45 classical techniques for front-end development

Keywords: Javascript Attribute JSON Java

Front-end development QQ group: 328058344, forbid chatting, do not enter unless you like it!


1. The first time to assign variables is to remember to use the VaR keyword (chat: remember clearly once to the front of the interview, a project manager met me and another person at the same time. The interviewer started by asking us to write an array to duplicate functions, and then finished the assignment with a crash. The interviewer looked down and gave it to a competitor directly, asking her to point out the mistakes in my code. I just forgot to write var declaration variable, and blushed instantly. =. = ~ ~

Regression Topic: If a variable does not declare a direct assignment, it will default to be a global variable (all the ownerless ones are window s), so avoid global variables as much as possible.

Note: Failure to declare will result in an error in strict mode.

2. Use "===" instead of "==", that is, equal substitution and so on.

Reason: == and=! Operators have implicit conversions, resulting in "==" slower, try to use all equals.

Interview question: console. log ([]= false); what to output? The output is true, and the implicit conversion between the two sides is converted to (0==0).

Console. log ([]==== false) output false

3. The logical results of underfined, null, 0, false, NaN, "(control string) are all false.

This feature can be used to reduce code such as if(data!=0){console.log(data)};

It can be written as if(data){console.log(data)};

Some children's shoes may be reduced to data & console. log (data);

The effect is the same, but the amount of code is reduced a little, but still pay attention to some code style, some companies have requirements...

(Good code is like poetry, bad code is like shit), (cough)~~

4. Use semicolons at the end of the line.

In practice, it's better to use semicolons. It's OK to forget to write. In most cases, it's OK to use semicolons. JavaScript Interpreters are automatically added.

Influence:

return

{a=1}

If you don't add ";", the js parser will turn you into a __________

return;

{a=1};

Then you can only cry.

Suggestion: Keep good coding habits and use a powerful error-checking editor like WebStorm.

5. Use Object Constructor

  1. function person(firstName,lastName){  
  2.     this.firstName = firstName;  
  3.     this.lastName = lastName;  
  4. }  
  5. var saad = new person('susan','bigDou');  

6. Be careful with typeof, instanceof, contructor

typeof:Javascript unary operator, used to return the original type of variable in the form of a string. Note that typeof null, most object types (Array, Time Date, etc.) return objects. Check whether the array is an array.

http://blog.csdn.net/u013084331/article/details/51150387

contructor: Internal Prototype Properties

instanceof:JavaScript operator, which searches in the constructor of the prototype, returns true if found, or false if not.

  1. var arr = ["a""b""c"];  
  2. typeof arr;   //Return to "object"  
  3. arr instanceof Array // true  
  4. arr.constructor();  //[]  
7. Use self-tuning functions

Functions are automatically executed directly after they are created, assimilated into what is called a self-tuning anonymous function, or call function expressions directly. The code is as follows:

  1. (function(){  
  2.     //The code placed here will be executed automatically  
  3. })();    
  4. (function(a,b){  
  5.     var result = a+b;  
  6.     return result;  
  7. })(10,20)  
8. Getting members from arrays

  1. var items = [12, 548 , 'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' , 2145 , 119];  
  2. var  randomItem = items[Math.floor(Math.random() * items.length)];  
9. Get random numbers in a specified range

This function is generated test False data are used in particular, such as the number of wages in the specified range.

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

10. Generate an array of numbers from 0 to a specified number

  1. var numbersArray = [] , max = 100;  
  2. forvar i=1; numbersArray.push(i++) < max;);  // numbers = [1,2,3 ... 100]  
Note that arr.push(num) returns arr.length after push

11. Generating random alphanumeric strings

  1. function generateRandomAlphaNum(len) {  
  2.     var rdmString = "";  
  3.     for( ; rdmString.length < len; rdmString  += Math.random().toString(36).substr(2));  
  4.     return  rdmString.substr(0, len);  
  5. }  
12. Disturbing the order of digital arrays

  1. var numbers = [5, 458 , 120 , -215 , 228 , 400 , 122205, -85411];  
  2. numbers = numbers.sort(function(){ return Math.random() - 0.5});  
  3. /* numbers The array will be similar to [120, 5, 228, -215, 400, 458, -85411, 122205].*/  
JavaScript's built-in array sorting function is used here, and a better way is to implement it in specialized code (such as the Fisher-Yates algorithm), as discussed in StackOverFlow.

13. String space removal

Java , C# and PHP Some other languages have implemented special string de-space functions, but they are not available in JavaScript. We can use the following code to give String object functions a trim function:

  1. String.prototype.trim = function(){return this.replace(/^\s+|\s+$/g,"");};  
The new JavaScript engine already has a native implementation of trim().

14. Addition between arrays

  1. var array1 = [12 , "foo" , {name "Joe"} , -2458];  
  2. var array2 = ["Doe" , 555 , 100];  
  3. Array.prototype.push.apply(array1, array2);  
  4. /* array1 The values are [12,'foo,'{name,'Joe'}, -2458,'Doe,'555, 100]*/  
15. Converting objects to arrays

  1. var argArray = Array.prototype.slice.call(arguments);  
16. Verify that it is a number

  1. function isNumber(n){  
  2.     return !isNaN(parseFloat(n)) && isFinite(n);  
  3. }  
17. Verify that it is an array

  1. function isArray(obj){  
  2.     return Object.prototype.toString.call(obj) === '[object Array]' ;  
  3. }  
18. Get the maximum and minimum values in an array

  1. var  numbers = [5, 458 , 120 , -215 , 228 , 400 , 122205, -85411];   
  2. var maxInNumbers = Math.max.apply(Math, numbers);   
  3. var minInNumbers = Math.min.apply(Math, numbers);  

19. Clear arrays

  1. var myArray = [12 , 222 , 1000 ];    
  2. myArray.length = 0; // myArray will be equal to [].  
20. Do not delete or remove elements directly from an array

If delete is used directly for an array element, it is not deleted, but the element is set to undefined. Array element deletion should use splice.

Avoid:

  1. var items = [12, 548 ,'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' ,2154 , 119 ];   
  2. items.length; // return 11   
  3. delete items[3]; // return true   
  4. items.length; // return 11   
  5. /* items The results were [12, 548,'a', undefined * 1, 5478,'foo', 8852, undefined * 1,'Doe', 2154, 119].*/  
And should:

  1. var items = [12, 548 ,'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' ,2154 , 119 ];   
  2. items.length; // return 11   
  3. items.splice(3,1) ;   
  4. items.length; // return 10   
  5. /* items The result is [12, 548, "a", 5478, "foo", 8852, undefined × 1, "Doe", 2154, 119]  
delete can be used when deleting attributes of an object.

21. Truncate arrays using the length attribute

In the previous example, the length attribute is used to empty the array, and it can also be used to truncate the array:

  1. var myArray = [12 , 222 , 1000 , 124 , 98 , 10 ];    
  2. myArray.length = 4; // myArray will be equal to [12 , 222 , 1000 , 124].  
At the same time, if the length attribute is enlarged and the length value of the array increases, undefined is used to fill in the new element. Length is a writable property.

  1. myArray.length = 10; // the new array length is 10   
  2. myArray[myArray.length - 1] ; // undefined  
22. Use logic and or in conditions

  1. var foo = 10;    
  2. foo == 10 && doSomething(); // is the same thing as if (foo == 10) doSomething();   
  3. foo == 5 || doSomething(); // is the same thing as if (foo != 5) doSomething();  
Logic can also be used to set default values, such as default values for function parameters.

  1. function doSomething(arg1){   
  2.     arg1 = arg1 || 10; // arg1 will have 10 as a default value if it's not already set  
  3. }  
23. Making map() Function Method Circulate Data

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

  1. var num =2.443242342;  
  2. num = num.toFixed(4);  // num will be equal to 2.4432  
Note that toFixec() returns a string, not a number.

25. Floating Point Computation

  1. 0.1 + 0.2 === 0.3 // is false   
  2. 9007199254740992 + 1 // is equal to 9007199254740992  
  3. 9007199254740992 + 2 // is equal to 9007199254740994  
Why? Because 0.1 + 0.2 equals 0.30000000000004. JavaScript numbers are built in accordance with the IEEE 754 standard and are represented by 64-bit floating-point decimals internally. See how the numbers in JavaScript are.

Code.

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

26. Check the attributes of objects through for-in loops

The following usage prevents iteration from entering the object's prototype properties.

  1. for (var name in object) {    
  2.     if (object.hasOwnProperty(name)) {   
  3.         // do something with name  
  4.     }    
  5. }  
Comma Operator

  1. var a = 0;   
  2. var b = ( a++, 99 );   
  3. console.log(a);  // a will be equal to 1   
  4. console.log(b);  // b is equal to 99  

Temporary storage of variables for computation and query

stay jQuery In the selector, you can temporarily store the entire DOM element.

  1. var navright = document.querySelector('#right');   
  2. var navleft = document.querySelector('#left');   
  3. var navup = document.querySelector('#up');   
  4. var navdown = document.querySelector('#down');  
29. Check the parameters passed in isFinite() in advance

isFinite (number) is a JavaScript built-in function to determine whether a number object can be converted to a finite number

  1. isFinite(0/0) ; // false  
  2. isFinite("foo"); // false  
  3. isFinite("10"); // true  
  4. isFinite(10);   // true  
  5. isFinite(undefined);  // false  
  6. isFinite();   // false  
  7. isFinite(null);  //true, this should be paid special attention to  
30. Avoid using negative numbers as indexes in arrays

  1. var numbersArray = [1,2,3,4,5];  
  2. var from = numbersArray.indexOf("foo") ;  // from is equal to -1  
  3. numbersArray.splice(from,2);    // will return [5]  
Note that the index parameter passed to splice is not negative, and when it is negative, elements are deleted from the end of the array.

31. Serialization and deserialization with JSON

  1. var person = {name :'Saad', age : 26, department : {ID : 15, name : "R&D"} };  
  2. var stringFromPerson = JSON.stringify(person);  
  3. /* stringFromPerson The result is "{name":"Saad", "age": 26, "department":{ID": 15", "name":"R&D"}.*/  
  4. var personFromString = JSON.parse(stringFromPerson);  
  5. /* personFromString The value is the same as the person object.*/  
32. Do not use eval() or function constructors

eval() and Function Constructor are expensive. Every time they are called, the JavaScript engine converts the source code into executable code.

  1. var func1 = new Function(functionCode);  
  2. var func2 = eval(functionCode);  
33. Avoid using with()

Variables can be added to the global scope by using with(), so if there are other variables with the same name, it is easy to confuse and the binary values will be overwritten.

34. Do not use for-in for arrays

Avoid:

  1. var sum = 0;    
  2. for (var i in arrayNumbers) {    
  3.     sum += arrayNumbers[i];    
  4. }  
And should:

  1. var sum = 0;    
  2. for (var i = 0, <span style="color:#cc0000;">len = arrayNumbers.length; i < len</span>; i++) {    
  3.     sum += arrayNumbers[i];    
  4. }  
Another advantage is that the i and len variables are in the first declaration of the for loop, and they are initialized only once, which is faster than the following:
  1. for (var i = 0; i < arrayNumbers.length; i++)  
35. Use functions instead of strings when passing setInterval() and setTimeout().

If you pass a string to setTimeout() and setInterval(), they will convert it in a way similar to eval, which is certainly slower, so don't use:

  1. setInterval('doSomethingPeriodically()', 1000);    
  2. setTimeout('doSomethingAfterFiveSeconds()', 5000);  
They are:

  1. setInterval(doSomethingPeriodically, 1000);    
  2. setTimeout(doSomethingAfterFiveSeconds, 5000);  
36. Use switch/case instead of a stack of if/else

switch/case is quicker, more elegant, and more conducive to code organization when judging that there are more than two branches. Of course, if there are more than 10 branches, don't use switch/case.

37. Use digital intervals in switch/case

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

  1. function getCategory(age) {    
  2.     var category = "";    
  3.     switch (true) {    
  4.         case isNaN(age):    
  5.             category = "not an age";    
  6.             break;    
  7.         case (age >= 50):    
  8.             category = "Old";    
  9.             break;    
  10.         case (age <= 20):    
  11.             category = "Baby";    
  12.             break;    
  13.         default:    
  14.             category = "Young";    
  15.             break;    
  16.     };    
  17.     return category;    
  18. }    
  19. getCategory(5);  //To return to "Baby"  
38. Prototype using object as object

In this way, a given object can be used as a parameter to create a new object based on this prototype:

  1. function clone(object) {    
  2.     function OneShotConstructor(){};   
  3.     OneShotConstructor.prototype = object;    
  4.     return new OneShotConstructor();   
  5. }   
  6. clone(Array).prototype ;  // []  
39. HTML Field Conversion Function

  1. function escapeHTML(text) {    
  2.     var replacements= {"<""<"">"">","&""&""\"""""};                        
  3.     return text.replace(/[<>&"]/g, function(character) {    
  4.         return replacements[character];    
  5.     });   
  6. }  
40. Do not use try-catch-finally inside a loop

The catch part of try-catch-final assigns exceptions to a variable during execution, which is constructed as a new variable in the runtime scope.

Avoid:

  1. var object = ['foo''bar'], i;    
  2. for (i = 0, len = object.length; i <len; i++) {    
  3.     try {    
  4.         // do something that throws an exception   
  5.     }    
  6.     catch (e) {     
  7.         // handle exception    
  8.     }   
  9. }  
And should:

  1. var object = ['foo''bar'], i;    
  2. try {   
  3.     for (i = 0, len = object.length; i <len; i++) {    
  4.         // do something that throws an exception   
  5.     }   
  6. }   
  7. catch (e) {     
  8.     // handle exception    
  9. }  
41. Pay attention to setting timeouts when using XMLHttpRequests

When XMLHttpRequests are executed, when there is no response for a long time (such as a network problem, etc.), the connection should be aborted, which can be accomplished by setTimeout():

  1. var xhr = new XMLHttpRequest ();   
  2. xhr.onreadystatechange = function () {    
  3.     if (this.readyState == 4) {    
  4.         clearTimeout(timeout);    
  5.         // do something with response data   
  6.     }    
  7. }    
  8. var timeout = setTimeout( function () {    
  9.     xhr.abort(); // call error callback    
  10. }, 60*1000 /* timeout after a minute */ );   
  11. xhr.open('GET', url, true);    
  12. xhr.send();  
Also note that you should not send multiple XMLHttpRequests.

42. Dealing with WebSocket timeouts

Usually, after a WebSocket connection is created, if there is no activity within 30 seconds, the server side will timeout the connection, and the firewall can also timeout the connection that is not active per unit cycle.

To prevent this from happening, an empty message can be sent to the server at regular intervals. This requirement can be achieved through the following two functions, one for keeping the connection active and the other for ending the state.

  1. var timerID = 0;   
  2. function keepAlive() {   
  3.     var timeout = 15000;    
  4.     if (webSocket.readyState == webSocket.OPEN) {    
  5.         webSocket.send('');    
  6.     }    
  7.     timerId = setTimeout(keepAlive, timeout);    
  8. }    
  9. function cancelKeepAlive() {    
  10.     if (timerId) {    
  11.         cancelTimeout(timerId);    
  12.     }    
  13. }  

The keepAlive() function can be placed at the end of the onOpen() method of a WebSocket connection and cancelKeepAlive() at the end of the onClose() method.

43. Always note that the original operator is faster than the function call, using Vanilla JS

For example, this is not usually the case:

  1. var min = Math.min(a,b);   
  2. A.push(v);  
It can be replaced by:
  1. var min = a < b ? a : b;   
  2. A[A.length] = v;  
Editor's Note: Here I remember that Math performance is better than a simple comparison statement loop 10 times, each time 1 billion, Math (a,b) execution time is well described as about 3900, a < b? A: B is about 4300, push and Array.length performance.

Not many, test environment chrome, you can also test under their own.

44. Pay attention to code structure during development, check and compress JavaScript code before going online

Tools such as JSLint or JSMin can be used to check and compress code.

45. JavaScript is extensive and profound. Here are some good learning resources.

Code Academy Resources: http://www.codecademy.com/tracks/javascript

Eloquent JavaScript written by Marjin Haverbekex: http://eloquent JavaScript .NET/

Advanced JavaScript by John Resig: http://ejohn.org/apps/learn/

Front-end development QQ group: 328058344, forbid chatting, do not enter unless you like it!

Posted by el_kab0ng on Sun, 21 Apr 2019 22:45:36 -0700