This first article will talk about some programming details of NodeJs.
1. Iterate through the array
for (var i=0, l=arr.length; i<l; i++)
One advantage of writing this way is to get the operation of getting the length of the array object by one less step in each loop. The longer the array length, the more obvious the value.
2. Determine the authenticity of variables
if (a) {...} //a='', a='0', a=[], a={}The results of if conditional judgment are: false, true, true, true. This result is different from the result of PHP, so don't be confused. It is also necessary to distinguish between situations where it is similar to non-identity judgments.
3. Non-identity judgment of 0 value
1 if (0 == '0') {...} //true2 if (0 == []) {...} //true3 if (0 == [0]) {...} //true4 if (0 == {}) {...} //false5 if (0 == null) {...} //false6 if (0 == undefined) {...} //falseIn fact, there are many such strange judgments, and I only listed the more common ones. If you want to understand the rules, please refer to another blog post of my: [JavaScript] In-depth analysis of JavaScript's relational operations and if statements.
4. The trap of parseInt
var n = parseInt(s); //s='010'
After the statement is executed, n value is 8, not 10. Although many people know this, it is inevitable that there will be mistakes in programming, and I have a deep understanding of it. Therefore, it is best to write in the following way, so there will be no errors.
var n = parseInt(s, 10);
5. Must declare variables before use
Although it will not make any mistakes directly using variables without declaring them, it is easy to make any mistakes when writing in this way. Because the interpreter interprets it as a global variable, it is easy to cause errors by dividing it with other global variables. Therefore, you must develop the good habit of declaring variables before using them.
6. There is async in the loop
for (var i=0, l=arr.length; i<l; i++) { var sql = "select * from nx_user"; db.query(sql, function(){ sys.log(i + ': ' + sql); }); //db.query is a table query operation, which is an asynchronous operation}You will find that the output results are the same, and are the output content when i=arr.length-1. Because JavaScript is single-threaded, it will execute the synchronous content of the complete loop before performing the asynchronous operations. The anonymous callback function in the code is an asynchronous callback. When the function is executed, the for loop and some subsequent synchronization operations have been executed. Due to the closure principle, this function will retain the contents of the SQL variable and the i variable of the last loop of the for loop, which will lead to an incorrect result.
So what should I do? There are two solutions, one is to use the immediate function, as follows:
for (var i=0, l=arr.length; i<l; i++) { var sql = "select * from nx_user"; (function(sql, i){ db.query(sql, function(){ sys.log(i + ': ' + sql); }); //db.query is a table query operation, which is an asynchronous operation})(sql, i);}Another method is to extract the asynchronous operation part and write a single function, as follows:
var outputSQL = function(sql, i){ db.query(sql, function(){ sys.log(i + ': ' + sql); }); //db.query is a table query operation, which is an asynchronous operation}for (var i=0, l=arr.length; i<l; i++) { var sql = "select * from nx_user"; outputSQL(sql, i); }7. When processing large amounts of data, try to avoid loop nesting.
Because the processing time of loop nesting will increase exponentially with the increase in the amount of data, it should be avoided as much as possible. In this case, if there is no better way, the general strategy is to exchange space for time, that is, to establish a Hash mapping table of secondary cyclic data. Of course, specific situation analysis is also required. Another thing to say is that some methods are loop bodies themselves, such as Array.sort() (this method should be implemented with two layers of loops), so you need to pay attention when using it.
8. Try to avoid recursive calls.
The advantage of recursive calls is that the code is concise and the implementation is simple, while its disadvantages are very important. The following description is as follows:
(1) The size of the function stack will grow linearly with the recursive level, and the function stack has an upper limit value. When the recursive reaches a certain number of layers, the function stack will overflow, resulting in program errors;
(2) Each recursive layer will add additional stack pressing and stack release operations, that is, the saving site and recovery site during function call.
Therefore, recursive calls should be avoided as much as possible.
9. Regarding the scope isolation of module files.
When Node compiles JavaScript module files, its content has been wrapped in the beginning and end, as follows:
(function(exports, require, module, __filename, __dirname){ your JavaScript file code});This allows scope isolation between each module file. Therefore, when you write NodeJs module files, you don’t need to add another layer of scope isolation encapsulation. For example, the following code format will only add an additional layer of function calls, which is not recommended:
(function(){ ... …})();10. Don't mix arrays and objects
Here is an example of the error code:
var o = [];o['name'] = 'LiMing';
Mixed arrays and objects may lead to unpredictable errors. A colleague of mine encountered a very strange problem. Let’s look at the code first:
var o = [];o['name'] = 'LiMing';var s = JSON.stringify(o);
He thought that the name attribute of object o would be in the JSON string, but the result was nothing. I was also very strange at the time, but I had a premonition that it was a problem of mixing arrays and objects. I tried it and it was indeed its problem. Later I found in the ECMA specification that arrays are serialized according to JA rules. Therefore, you must develop a good programming habit, use arrays and objects correctly, and do not mix them.
11. Promise elegant programming
I believe that people who have been exposed to nodeJs have had this experience. When the asynchronous callback is nested in the asynchronous callback, the code seems very confusing and lacks ease of readability. This dilemma of nodeJs can be overcome with promises. promise is like a sculpting tool that makes your code elegant and beautiful. There is an A+ specification for promises, and there are several implementation methods online, you can refer to it.