My NodeJs learning Summary (1) and nodejs learning Summary

Source: Internet
Author: User

My NodeJs learning Summary (1) and nodejs learning Summary

In the 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 is to allow each loop to get the length of the array object step by step. The longer the array length, the more obvious the value.

2. Determine whether a variable is true or false

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

If conditions are judged as follows: false, true. This result is different from the PHP result. Do not confuse it. It is also necessary to distinguish between non-constant and similar cases.

3. Non-constant identification of 0 values

1 if (0 == '0') {...} //true2 if (0 == []) {...} //true3 if (0 == [0]) {...} //true4 if (0 == {}) {...} //false5 if (0 == null) {...} //false6 if (0 == undefined) {...} //false

In fact, there are many such strange judgments. I only listed the more common ones. If you want to understand the rules, refer to another blog: [JavaScript] to deeply analyze JavaScript relational operations and if statements.

4. parseInt traps

var n = parseInt(s); //s='010'

After the statement is executed, the n value is 8 instead of 10. Although many people know this, it is inevitable that errors will occur in programming. Therefore, it is best to write in the following way to avoid errors.

var n = parseInt(s, 10);

5. variables must be declared before use

Although directly using variables without declaring them will not cause errors, it is easy to write errors. Because the interpreter interprets it as a global variable, it is easy to duplicate the name with other global variables, resulting in errors. Therefore, we must develop a good habit of declaring variables before they are used.

6. asynchronous Loops

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, asynchronous operation}

You will find that the output results are the same and the output content is when I = arr. length-1. Because JavaScript is single-threaded, it will first execute the full loop of synchronous content before executing the asynchronous operation. 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 completed. Out of the closure principle, this function will retain the SQL variables and I variable content of the last loop of the for loop, so it will lead to incorrect results.

What should we do? There are two solutions: one is to use the immediate function, as shown below:

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. Avoid loop nesting when processing a large amount of data.

Because the processing time of loop nesting will increase exponentially as the data volume increases, we should avoid it as much as possible. In this case, if there is no better way, the general strategy is to change the space for time, that is, to create a Hash ing table for the second-level cyclic data. Of course, we need to analyze the specific situation. Another point is that some methods are itself a loop body, such as Array. sort () (This method should be implemented using a two-layer loop). Pay attention when using it.

8. Avoid recursive calls whenever possible.

The advantage of recursive calling is that the Code is concise and easy to implement, and its disadvantages are very important, as described below:

(1) The size of the function stack increases linearly with the recursive hierarchy, and the function Stack has an upper limit. When the recursion reaches a certain number of layers, the function stack overflows, leading to program errors;

(2) Each recursive layer will add additional stack pressure and out-of-stack operations, that is, saving and restoring the site during the function call process.

Therefore, recursive calls should be avoided as much as possible.

9. Scope isolation of module files.

When compiling a JavaScript module File, Node has packaged its content at the beginning and end, as shown below:

(Function (exports, require, module, _ filename, _ dirname) {Your JavaScript file code });

In this way, the scope of each module File is isolated. Therefore, when writing node. js module files, you do not need to add scope isolation encapsulation. The following code format only adds an additional layer of function calls, 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 may 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 that the name attribute of the object o would be in the JSON string, and the result was no. I was surprised at the time, but I had a hunch that it was a problem to mix arrays and objects. I tried it and it was really a problem. Later I found in the ECMA specification that arrays are serialized according to JA rules. Therefore, we need to develop a good programming habit, correct use of arrays and objects, and do not mix them.

11. promise elegant Programming

I believe that anyone who has been familiar with node. js has had such an experience. When nested asynchronous callbacks in asynchronous callbacks, the code looks messy and lacks the ease of coding. This dilemma of nodeJs can be overcome by promise. Promise is like a carving tool, making your code elegant and beautiful. Promise has A + specification. There are several implementation methods on the Internet. For more information, see.


Learning Summary (help me write a learning Summary of 800 words)

Summary

One semester soon passed, but this time the mood was very different from the previous one. The feeling of returning to the arrow was early covered by the bad feelings of the exam. Think about how to tell your parents if the exam is not good? In particular, this time I spent a lot of time dealing with CET4, so I took all my other homework. So I did a very little bit about my review work on this exam, but now I think it is not worth the candle. Especially now. all rights reserved are still uncertain about whether or not I can pass level 4. No matter what the test result is, I will have to redouble my efforts next semester, and I will definitely get rid of the old problem of being eccentric, strive to learn each course in a down-to-earth manner.
The sophomore year we had already walked out of the ivory tower and began to try to contact the society. I remember that when I was a freshman, I often felt a little better at being a computer student. However, it is hit by some feedback from the talent market. Now I have to prepare for the upcoming job crisis. Originally, we all know that the brand of our school is not very hard. Secondly, the job situation in our computer industry is getting increasingly tense. Thirdly, I am a girl and a girl who studies computers. I have heard that many companies have said, "I 'd rather have the worst boys than the best girls ." It's so angry to say. But what can we do in the face of these extreme social phenomena? The only thing we can do is to improve our own conditions.
I have been used to the tense and relaxed atmosphere of my college life for more than two years. Although the courses are still arranged very compact, my spare time has obviously increased, it makes me feel that my college life is so rich and colorful that my familiar friends are no longer at school. So far, I have had a good relationship with the people in the dormitory. Although sometimes there may be a small holiday, it is also very good. all rights reserved. I am glad to be able to come to Huai Gong sometimes. Otherwise, I will not be able to make so many intimate friends. A university is not only a place for us to exchange knowledge, but also a place for us to learn how to behave and access society. I feel that my current education is at all levels, so I will take advantage of this rare opportunity, cherish this precious time, and strictly demand myself, strive to be a qualified college student.

How to Write a weekly summary? (Learned)

In the last week of the last semester, our class finally ushered in a long-awaited weekly work. Maybe it's the first time in my high school career. Everyone's face is filled with an excited expression: this is a huge test of our capabilities! We were very pleased with the fact that we completed our tasks well and did not drop our scores when we were busy.
However, the biggest benefit of this week is that we have learned about unity and the significance of cooperation. For example, in our etiquette group, we arrived in advance every day and gave up a lot of rest time. Although it was very hard, everyone persisted. Every time the teacher walks past, we send sincere greetings to the teacher. Every time we check the class, the students in charge of this part stand in front of the door early, they check as required, give appropriate reminders, and score.
We learned how to work hard, how to exercise, and how to learn many things.

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.