Front-end development QQ group: 328058344, forbid chatting, do not enter unless you like it!
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
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.
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:
8. Getting members from arrays
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.
10. Generate an array of numbers from 0 to a specified number
Note that arr.push(num) returns arr.length after push
11. Generating random alphanumeric strings
12. Disturbing the order of digital arrays
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:
The new JavaScript engine already has a native implementation of trim().
14. Addition between arrays
15. Converting objects to arrays
16. Verify that it is a number
17. Verify that it is an array
18. Get the maximum and minimum values in an array
19. Clear arrays
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:
And should:
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:
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.
22. Use logic and or in conditions
Logic can also be used to set default values, such as default values for function parameters.
23. Making map() Function Method Circulate Data
24. Keep the specified decimal digits
Note that toFixec() returns a string, not a number.
25. Floating Point Computation
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.
Comma Operator
Temporary storage of variables for computation and query
stay jQuery In the selector, you can temporarily store the entire DOM element.
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
30. Avoid using negative numbers as indexes in arrays
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
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.
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:
And should:
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:
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:
They are:
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:
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:
39. HTML Field Conversion Function
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:
And should:
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():
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.
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:
It can be replaced by:
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!
Front-end development QQ group: 328058344, forbid chatting, do not enter unless you like it!