"NodeJs" My NodeJs Technical Summary--first article

Source: Internet
Author: User

Since it is my technical summary, that is, based on my skill level, write shallow everyone do not joke, if there is wrong place also look correct.

This first article is about some of the programming details of Nodejs.

1. Iterating through an array

 for (var i=0, l=arr.length; i<l; i++)

One of the benefits of writing this is to get the array object length one step at a time, and the longer the array length, the more significant the value.

2. Judging the true and false of variables

if (a) {...}//a= ', a= ' 0 ', a=[], a={}

The result of the If condition judgment is: false, True, true, true. This result and PHP results are different, do not confuse. You also need to differentiate between it and non-identical judgments.

3, 0 value non-identical judgment

1 if (0 = = ' 0 ') {...}//true 2 if (0 = = []) {...}//true 3 if (0 = = [0]) {...}//true 4 if (0 = = {}) {...}//false 5 if NULL {...}//false6if (0 = = undefined) {...}//false

In fact, there are many such strange judgments, I only listed the more common. If you want to figure out the rules, see my other blog post: "JavaScript" delves into JavaScript's relational operations and if statements.

4, the parseint Trap

var // s= ' 010 '

The statement executes after the N value is 8, not 10. Although a lot of people know this, but the programming will inevitably error, I have deep experience. Therefore, it is best to write in the following way, it will not be wrong.

var n = parseint (s, 10);

5, the variable must first declare before using

Although it is not an error to use variables directly without declaring them, it is easy to make mistakes. Because the interpreter interprets it as a global variable, it is easy to duplicate the name of another global variable and cause an error. So, be sure to develop a good habit to declare before using variables.

6. There is an asynchronous situation in the loop

 for (var i=0, l=arr.length; i<l; i++) {
var sql = "Select * from Nx_user"; function () { Sys.log (i + ': ' + sql); // db.query is a table query operation, which is an asynchronous operation }

You will find that the output is the same, and is the output when i=arr.length-1. Because JavaScript is single-threaded, it executes the asynchronous operation of the entire loop after it has finished synchronizing the contents. The anonymous callback function in the code is an asynchronous callback. When the function is executed, the for loop and some subsequent synchronizations have been performed. For the closure principle, the function retains the contents of the SQL variable and the I variable for the last loop of the For loop, so it results in an incorrect result.

What about that? There are two ways to solve this, 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) {        function() {            + ': ' + sql);         // db.query is a table query operation, which is an asynchronous operation     }) (sql, i);}

Another way is to extract the asynchronous operation part, write a function, as follows:

var outputsql = function (sql, i) {      db.query (SQL, function () {            " ) + sql);     // db.query is a table query operation, which is an asynchronous operation } for (var i=0, l=arr.length; i<l; i++var"  SELECT * from Nx_user";   Outputsql (sql, I); }

7, in the processing of large amounts of data, as far as possible to avoid circular nesting.

Because the processing time of the loop nesting increases exponentially number of times as the amount of data is increased, it should be avoided as much as possible. In this case, if there is no better way, the general strategy is to space-time, that is, the establishment of a two-level cyclic data hash mapping table. Of course, there is a specific analysis of specific circumstances. Another thing to say is that some of the methods themselves are a loop body, such as Array.Sort () (this method should be implemented with a two-layer loop), which should be noted when used.

8, try to avoid recursive calls.

The advantage of recursive invocation is that the code is concise, the implementation is simple, and its shortcomings are important, explained as follows:

(1) The size of the function stack increases linearly with the recursive hierarchy, and the function stack is capped, and the function stack overflows when the recursion reaches a certain number of layers, resulting in a program error;

(2) Each recursive layer will add additional stack and stack operations, that is, the function calls the process of saving the site and recovery site.

Therefore, you should try to avoid recursive calls.

9, about the module file scope isolation.

When node compiles the JavaScript module file, it has already wrapped its contents in a tail-wrap, as follows:

(function(exports, Require, module, __filename, __dirname) {    your JavaScript file code});

This allows for scope isolation between each module file. Therefore, when you write the Nodejs module file, you do not need to add a layer of scope isolation encapsulation. As in the following code format, only an additional layer of function calls will be added, which is not recommended:

(function() {   ...}) ();

10. Do not mix arrays and objects

The following is an example of the error code:

var o = [];o[' name '] = ' liming ';

Mixing arrays and objects can cause unpredictable errors. One of my colleagues encountered a very strange problem, first look at the code:

var o = [];o[' name '] = ' liming '; var s = json.stringify (o);

He thought the object O's name attribute would be in the JSON string, and the result would be no. I was strange at the time, but I had a hunch that it was a problem with arrays and objects mixing, and it was really a problem. Later I found in the ECMA specification that the array was serialized by the Ja Rule. Therefore, to develop a good programming habit, the correct use of arrays and objects, do not mix.

11, Promise Elegant programming

It is believed that people who have been exposed to Nodejs have experienced this, and when asynchronous callbacks are nested in asynchronous callbacks, the code becomes chaotic and lacks legibility. This dilemma of Nodejs can be overcome by promise. Promise is like a crafting device that makes your code elegant and beautiful. Promise has a A + specification, there are several implementations on the web, you can see, you can also look at my other blog post: Implementation of Nodejs promises library (based on Promise.js rewrite)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.