In this first article, let’s talk about some programming details of NodeJs.
1. Traverse the array
for (var i=0, l=arr.length; i<l; i++)
One advantage of writing this way is that each loop saves one step to obtain the length of the array object. The longer the array length, the more obvious the value.
2. Determine whether the variable is true or false
if (a) {...} //a='', a='0', a=[], a={}
The results of if conditional judgment are: false, true, true, true. This result is different from PHP's result, don't be confused. It is also necessary to distinguish between situations where it is similar to non-identity judgments.
3. Judgment of non-identity of 0 value
1 if (0 == '0') {...} //true 2 if (0 == []) {...} //true 3 if (0 == [0]) {...} //true 4 if (0 == {}) {...} //false 5 if (0 == null) {...} //false 6 if (0 == undefined) {...} //false
In fact, there are many such weird judgments, I only listed the more common ones. If you want to understand the rules, please refer to my other blog post: [JavaScript] In-depth analysis of JavaScript’s relational operations and if statements.
4. The trap of parseInt
var n = parseInt(s); //s='010'
After this statement is executed, the value of n is 8, not 10. Although many people know this, mistakes are inevitable in programming, and I know it very well. Therefore, it is best to write in the following way and you will not make mistakes.
var n = parseInt(s, 10);
5. Variables must be declared before use
Although there is no error in using variables directly without declaring them, writing this way is very error-prone. Because the interpreter will interpret it as a global variable, it can easily have the same name as other global variables and cause errors. Therefore, we must develop a good habit of declaring variables before using them.
6. There is asynchronous situation 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为表查询操作,是异步操作 }
You will find that the output results are the same, and they are the output content when i=arr.length-1. Because JavaScript is single-threaded, it will first execute the synchronous content of the entire loop before executing the asynchronous operations. The anonymous callback function in the code is an asynchronous callback. When this function is executed, the for loop and some subsequent synchronization operations have been completed. Due to the closure principle, this function will retain the contents of the sql variable and i variable in the last loop of the for loop, so it will lead to wrong results.
So what should we do? There are two solutions. One is to use an 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为表查询操作,是异步操作 })(sql, i); }
Another method is to extract the asynchronous operation part and write a function as follows:
var outputSQL = function(sql, i){ db.query(sql, function(){ sys.log(i + ': ' + sql); }); //db.query为表查询操作,是异步操作 } 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 nested loops.
Because the processing time of nested loops will increase exponentially as the amount of data increases, it should be avoided as much as possible. In this situation, if there is no better way, the general strategy is to trade space for time, that is, to establish a Hash mapping table of secondary cyclic data. Of course, specific circumstances must be analyzed on a case-by-case basis. Another point to mention is that some methods themselves are a loop body, such as Array.sort() (this method should be implemented using two layers of loops), so you need to pay attention when using it.
8. Try to avoid recursive calls.
The advantage of recursive calling is that the code is concise and the implementation is simple, but its disadvantages are very important and are explained as follows:
(1) The size of the function stack will grow linearly with the recursion level, and the function stack has an upper limit. When the recursion reaches a certain number of levels, the function stack will overflow, causing program errors;
(2) Each recursive level will add additional stack push and pop operations, that is, saving the scene and restoring the scene during the function call.
Therefore, recursive calls should be avoided as much as possible.
9. Regarding scope isolation of module files.
When Node compiles the JavaScript module file, its content has been packaged head and tail, as follows:
(function(exports, require, module, __filename, __dirname){ 你的JavaScript文件代码 });
This allows scope isolation between each module file. Therefore, when you write NodeJs module files, you do not need to add a layer of scope isolation encapsulation yourself. The following code format only adds an extra layer of function calls, which is not recommended:
(function(){ ... ... })();
10. Don’t mix arrays and objects
The following is an example of an error code:
var o = []; o['name'] = 'LiMing';
Mixing arrays and objects may lead to unpredictable errors. One of my colleagues encountered a very strange problem. Let’s look at the code first:
var o = []; o['name'] = 'LiMing'; var s = JSON.stringify(o);
He originally thought that the name attribute of object o would be in the JSON string, but the result was that it was not. I was also very surprised at the time, but I had a hunch that it was a problem of mixing arrays and objects. I tried it and it turned out to be the problem. Later, I found out in the ECMA specification that arrays are serialized according to JA rules. Therefore, it is necessary to develop a good programming habit, use arrays and objects correctly, and do not mix them.
11. Elegant Promise Programming
I believe anyone who has come into contact with nodeJs has had this experience. When asynchronous callbacks are nested within asynchronous callbacks, the code becomes confusing and lacks readability. This dilemma of nodeJs can be overcome with the help of promises. Promise is like a carver, making your code elegant and beautiful. Promise has an A specification, and there are several implementation methods online, you can refer to it.