NodeJs basic syntax and type, nodejs basic syntax

Source: Internet
Author: User
Tags define null php foreach

NodeJs basic syntax and type, nodejs basic syntax

Preface

Today, I want to check the knowledge about Node types. I want to summarize it and see an article on Googol, but the original link is gone. I will pull this article out of the snapshot, if the original author has a problem, contact me!

This article is the basis of some JS, and experts will skip it automatically! I have never written JavaScript before. This is relatively weak, so I encountered a problem when writing node. Here I will add some knowledge to myself!

Body

Node. js is based on the JavaScript script language. A common feature of most scripting languages is "weak type ".

Unlike PHP, PHP does not need to declare new variables, while JavaScript still needs to declare var. This var covers the meaning of all types in C ++ such as int, string, and char, and even function.

All the content in this and later articles is edited using vim in Linux or Cygwin (if not, convert it into your own method), and then you can view the results under the command line.

Basic syntax

Variable Declaration

In C/C ++, we declare the variable as follows:

'''C ++

Copy codeThe Code is as follows:
Void foo (){}
Int a = 0;
Char B = 'a ';
Float c = 1.0f;
Void (* d) () = foo; // <forget to write it like this. In short, it is a function pointer.

In Node. js, it is like this:
'''Javascript

Copy codeThe Code is as follows:
Function foo (){}
Var a = 0;
Var B = 'a ';
Var c = 1.0;
Var d = foo;

Therefore, no matter what type of variable, it is solved by a var in Node. js.

Loop statement

For... I

This loop statement is basically the same as C/C ++.

'''C ++

Copy codeThe Code is as follows:
For (int I = 0; I <foo; I ++)
{
//...
}

Since Node. js is of a weak type, you only need:
'''Javascript

Copy codeThe Code is as follows:
For (var I = 0; I <foo; I ++ ){
//...
}
For... In

This is a type of loop statement, similar to PHP foreach.

For example, we have a JSON object as follows:

Javascript

Copy codeThe Code is as follows:
Var foo = {
"Hello": "world ",
"Node": "js ",
"Blahblah": "bar"
};

At this time, we can use for... in to traverse the loop:

Javascript

Copy codeThe Code is as follows:
For (var key in foo ){
Console. log (key + ":" + foo [key]);
}

If we enter the following command in the command line:

Copy codeThe Code is as follows:
$ Node foo. js

The following content is displayed on the screen:

Copy codeThe Code is as follows:
Hello
: World
Node: js
Blahblah: bar

Tip: we can see from the above that the for... in statement is used to traverse the key names of JSON objects, arrays, and objects without providing key value traversal. If you want to obtain the key value, you can only obtain it in the form of foo [<current key name>. This is different from PHP foreach.

While... Do, do... Whill

This is not explained much. It is no big difference from other languages. It is nothing more than using var if there is a variable declaration.

Operator

+ ,-,*,/

This is also the case for these operators. Note that + is used. It can act on both strings and numerical operations. Although the type of a weak language is weak, numbers can sometimes appear in the form of strings, and strings can sometimes appear in the form of numbers, but when necessary, let's talk about its type. We can use the following code to check the result:

Copy codeThe Code is as follows:
Var a = "1 ";
Var B = 2;
Console. log (a + B );
Console. log (parseInt (a) + B );

Here, parseInt is a built-in function of Node. js. It parses a string into an int type variable.

The above code execution result is:

Copy codeThe Code is as follows:
12
3

Note: The first console. the log result is 12. Because a is a string, B is also added to the system as a string. The result is that the two strings are pasted together and changed to 12. The result of the second console. log is 3 because we convert the first a to the int type. The sum of the two int variables is the sum of the values, and the result is 3.

==,== ,! = ,! =

Here we need to explain that when the length of this logical operator is 2 (= ,! =). It only determines whether the external values are the same, rather than the type. For example

Copy codeThe Code is as follows:
Var a = 1, B = "1 ";
Console. log (a = B );

The output result is true. However, if we add an equal sign to the intermediate judgment, it is a strict judgment. It is true only when the types and values are the same; otherwise, it is false. That is to say

Copy codeThe Code is as follows:
Var a = 1, B = "1 ";
Console. log (a = B );

The returned result is false because a is of the int type and B is a string.

By the way, let's talk about conditional statements. In fact, the if here is no different from other languages, that is, there are several logical operators with two equal signs and three equal signs. So I won't go into details.

Typeof

Here I will regard it as an operator rather than a function.

This operator is used to determine the type of a variable and returns a string, that is, the type name. The specific code below will be known:

Copy codeThe Code is as follows:
Function foo (){}
Var a = 0;
Var B = 'hh ~ Sleep. ';
Var c = 1.0;
Var d = foo;
Var e = {"a": };
Var f = [1, 2, 3];
Var g = null;
Var h = undefined;
Console. log (typeof );
Console. log (typeof B );
Console. log (typeof c );
Console. log (typeof d );
Console. log (typeof e );
Console. log (typeof f );
Console. log (typeof g );
Console. log (typeof h );

The execution result here will be:

Copy codeThe Code is as follows:
Number
String
Number
Function
Object
Object
Object
Undefined

Null, undefined, NaN

In JavaScript, there are three special values, as shown in the title. The first one may be familiar to you. C/C ++ also contains uppercase letters, which is essentially

'''C ++

Define NULL 0

In JavaScript, the three values represent different meanings.

### Null ###

Null is a special object, which generally means null. For example:

Var a = null;
Everyone can understand it, so there is no more explanation. But unlike C/C ++, This null is not equal to 0.

### Undefined ###

This variable is not declared. In order to better distinguish null, the sample code is as follows:

'''Javascript

Copy codeThe Code is as follows:
Var a = {
"Foo": null
};
Console. log (a ["foo"]);
Console. log (a ["bar"]);

In the above Code, we set the value of a ["foo"] to null. It does not declare a ["bar"]. It is not even empty. We should have guessed the output:

Copy codeThe Code is as follows:
Null
Undefined

NaN

This is an empty value and a special number. Its full name is Not a Number. It's a bit strange. You can think of it as a number type variable that is not a numerical form or a number error.

Most of these errors occur when floating point numeric operations (such as Division by 0, you can even set a variable to NaN so that an error value is returned to let everyone know that this function has encountered an error.

Small debris

Other remaining statements are similar to other existing languages, such as break, switch, and continue.

Variable type

This section focuses on JavaScript objects. Other types are similar to each other.

Basic Type

Node. js contains the following basic types:

Number
String
Boolean
Array
The first three types of values can be assigned directly, while the array value assignment is only a reference value. If a value is changed in the new variable, the value of the old variable will also change, you can try the following code:

Javascript
Var foo = [1, 2, 3];
Var bar = foo;
Bar [0] = 3;
Console. log (foo );
The result is:

Javascript
[3, 2, 3]
That is to say, if an array is copied to a new array, it cannot be directly assigned, but it must be "Deep copy ".

It is necessary to introduce three methods for creating an array.

First:

Javascript

Copy codeThe Code is as follows:
Var dog = new Array ();
Dog [0] = "Hush ~ ";
Dog [1] = "egg soup ";
Dog [2] = "sleeping ";

Second:

Javascript
Copy codeThe Code is as follows:
Var dog = new Array ("Hush ~ "," Egg soup "," sleeping ");

Fourth:

Javascript
Copy codeThe Code is as follows:
Var dog = [
"Hush ~ ",
"Anetor ",
"Sleeping"
];

I personally prefer the third method, which is concise.

JSON object

Here, I pull out the JSON object separately Instead of classifying it as a JavaScript Object. If I think it is a bit wrong, I can skip this section directly.

Whether the distinction between a JSON object and a JavaScript Object is only used to store data, rather than the instantiation of a class. In fact, the essence of JSON is JavaScript Object Notation.

For more information about JSON, refer to our encyclopedia.

It is very easy to declare a JSON object in Node. js:

Javascript

Copy codeThe Code is as follows:
Var dog = {
"Pre": "Hush ~ ",
"Sub ":{
"Name": "anetable ",
"Act": "sleeping ",
"Time": 12
},
"Suf": ["I said", "it's sleeping", "it's sleeping"]
};

There are two ways to obtain the key value of a key name in the JSON object. The first is to use a dot join, and the second is to use brackets:

Javascript

Copy codeThe Code is as follows:
Dog
. Pre;
Dog ["pre"];

Note: When we use vertices, the keys in JSON are directly followed. If we regard the key as a variable, we can only use dog [key] to try it out: now try it by yourself and use... in to traverse the above JSON object. Don't forget to use typeof meow ~

Basics of classes (objects)

Strictly speaking, the class of Node. js cannot be regarded as a class. In fact, it is just a collection of functions and some member variables are added. Its essence is actually a function.

However, for the sake of popularity, we will refer to it as a "class" and instantiate it as an "object ".

Because a class has many function features, or its essence is a function, we may be able to explain the function basics without any worries.

Class description and instantiation

It is very easy to declare a class. Don't laugh:

Javascript
Function foo (){
//...
}
Now, we have written a foo class.

Really false ?! True.

Believe it? If you don't believe it, you can take a look at the following code:

Javascript
Var bar = new foo ();
Although it is a function, if it is written in this form (new), it is the instantiation of this class.

The so-called foo () is actually the constructor of the foo () class.

Member variables

There are two methods for member variables.

The first type is to use this. <variable name> in the class constructor or any constructor. You can declare a member variable at any time without affecting external use. Even if you use it before it is declared, there will be an undefined variable. So this is the first method:

Copy codeThe Code is as follows:
Javascript
Function foo (){
This. hello = "world ";
}

Note: only when this is added is the member variable of the call class. Otherwise, it is only a local variable in the function. You need to know whether this is the scope of the variable.

The second method is to declare the external declaration in the constructor or any member function. The format is <Class Name>. prototype. <variable name>:

Javascript

Copy codeThe Code is as follows:
Function foo (){
//...
}
Foo. prototype. hello = "world ";

No matter which method is the declaration of member variables, let's look at the effect:

Javascript

Copy codeThe Code is as follows:
Var bar = new foo ();
Console. log (bar. hello );

You can even modify this class as follows:

Javascript

Copy codeThe Code is as follows:
Function foo (){
This. hello = "world ";
}
Foo. prototype. hello = "la ";

And then use the above Code to output.

Think about why the output is "world" rather than "banquefutang.

Constructor

As we have said before, this foo () is actually a constructor. Obviously we can pass parameters to the constructor, so we have the following code:

Javascript

Copy codeThe Code is as follows:
// Code 2.1
Function foo (hello ){
If (hello = undefined ){
This. hello = "world ";
} Else {
This. hello = hello;
}
}

We can see that there is a wonderful judgment above, if (hello = undefined). What is the purpose of this judgment? The first possibility is that the developer intentionally uploads an undefined object to it, which is understandable.

There is another situation. At the beginning, we mentioned that JavaScript is a weak type language. In fact, it is not only a weak type, but also its parameter passing is not rigorous. You can upload more or less data (as long as you ensure that the program does not go wrong or the logic does not go wrong), in principle, it is acceptable. Multiple parameters are automatically ignored, while the missing parameters are supplemented with undefined.

Take a look at the following code to understand:

Javascript

Copy codeThe Code is as follows:
// Connect code 2.1
Var bar1 = new foo ();
Var bar2 = new foo ("anchor ");

Please output the hello variables of the two bar and you will find that one is world and the other is omedas. Obviously, when we declared the first bar1, it was automatically considered by Node. js:

Javascript

Copy codeThe Code is as follows:
Var bar1 = new foo (undefined );

So we can see it as world.

In this constructor, we can see that the passed parameter is hello, and a member variable in this class is this. hello. However, we have mentioned before that when this and this are not available, the parameter only acts on the constructor, and the one with this added is the member variable. You can use this to distinguish them immediately, so it doesn't matter even if they have the same name.

Member Functions

Member function declaration

The declaration of member functions is similar to that of the second declaration method of member variables, that is, <Class Name>. prototype. <function name >=< function>;

Javascript

Copy codeThe Code is as follows:
// Connect code 2.1
Function setHello (hello ){
This. hello = hello;
}
Foo. prototype. setHello = setHello;
Bar1.setHello ("egg pie ");

The above Code shows that we have implemented the setHello function of the foo class, which can be used to modify the value of foo. hello.

But is it a little troublesome to write this? Next I will talk about an important feature of JavaScript Functions.

★Anonymous Functions★

Most of the time, some of our functions are referenced or called only in one place, so it is not worth a name for this function, so we can temporarily write this function, let the person who references it directly reference it and the person who calls it call it. Therefore, the function name can be omitted, for example:

Javascript

Copy codeThe Code is as follows:
Function (hello ){
This. hello = hello;
}

How to reference or call it? If the class above needs to be referenced, it is written as follows:

Javascript

Copy codeThe Code is as follows:
Foo. prototype. setHello = function (hello ){
This. hello = hello;
}

This method is effective with the member function declaration, and saves a lot of code. In fact, basically, the declaration of class member functions adopts this anonymous function method.

As for how to make anonymous functions called? This is usually used to input a function called only by a function.

For example, we have a function prototype:

Javascript

Copy codeThe Code is as follows:
/**
* We will pass in two variables, a and B,
* After calculating the value of a + B, submit it to func (num)
* Output
*/
Function sumab (a, B, func ){
Var c = a + B;
Func (a, B, c );
}

For example, we have two versions of output functions, one for Chinese output and the other for English output. If you do not need anonymous functions, write them as follows:

Javascript

Copy codeThe Code is as follows:
Function zh (a, B, sum ){
Console. log (the value of a + "+" + B + "is:" + sum );
}
Function en (a, B, sum ){
Console. log (a + "plus" + B + "is" + sum );
}
Sumab (1, 2, zh );
Sumab (3, 4, en );

After executing this code, the output result will be:

The value of 1 + 2 is: 3
3 plus 4 is 7
If the code is in the form of an anonymous function, it will be:

Javascript

Copy codeThe Code is as follows:
Sumab (1, 2, function (a, B, sum ){
Console. log (the value of a + "+" + B + "is:" + sum );
});
Sumab (3, 4, function (a, B, sum ){
Console. log (a + "plus" + B + "is" + sum );
});

This form is usually used in callback functions. The callback mechanism is the essence of Node. js or JavaScript. This article will be introduced later.

Anonymous function declaration method of member function declaration

Although I mentioned it in the previous section, I 'd like to explain it again.

Generally, we use anonymous functions to declare member functions of the class, because that function is a member function of the class and won't be referenced or called separately elsewhere, so we have the following code:

Javascript

Copy codeThe Code is as follows:
// Connect code 2.1
Foo. prototype. setHello = function (hello ){
This. hello = hello;
}

In this way, the foo class has the setHello function.

2.3.4. randomness of Classes

This is what I mean. The randomness of classes means that you can modify your classes anywhere in JavaScript, which is similar to Ruby.

For example, string is actually a class with member variables such as length and member functions such as indexOf and substr. But if we think this string is not perfect in some places and want to add our own method, we can add a function to it where you want it, for example:

Javascript

Copy codeThe Code is as follows:
String. prototype. sb = function (){
Var newstr = "";
For (var I = 0; I <this. length; I ++ ){
If (I % 2 = 0) newstr + = "s ";
Else newstr + = "B ";
}
Return newstr;
};

This function is to fill in a string and turn it into the embodiment of sb.

Let's test:

Copy codeThe Code is as follows:
Var str = "~ Sleep. ";
Console. log (str. sb ());

You will get the following result:

Sbsbsbsbs
You told your computer ~ .", Your computer will scold you for being stupid for four and a half times. (Hit it quickly)

3. Attachment

3.1. Deep copy

The so-called deep copy is to create an array or object, manually copy the values of the source array or basic type variables in the object one by one, instead of simply taking the reference of the source array or object. So this involves a recursive call or something.

The following is a deep copy function that I implemented. You can write your own code and add it to your Node. js knowledge base.

Javascript

Copy codeThe Code is as follows:
Function cloneObject (src ){
Var dest = {};
For (var key in src ){
If (typeof src = "object") dest [key] = cloneObject (src [key]);
Else dest [key] = src [key];
}
Return dest;
}

Related Article

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.