Write in front
Today I want to check out the knowledge of Node types and what kind of knowledge I want to summarize. I saw an article on Google, but the original link is gone. I pulled this article out in the snapshot. If the original author has any questions, please contact me!
This article is all based on some JS, and experts will automatically skip it! I haven't written much about js before, and this aspect is relatively weak, so I also encountered trouble when writing nodes. Here is a supplement to my knowledge!
text
The basis of Node.js is JavaScript, the scripting language. One common feature of most scripting languages is "weak type".
Unlike PHP, even if there are new variables in PHP, there is no need to declare them, while JavaScript still needs var to declare them. This var covers all types of meanings such as int, string, char, etc. in C++, and even functions.
All content in this article and the following article are edited using vim in Linux or Cygwin (if not, please convert it into your own method), and then view the results under the command line.
Basic syntax
Variable declaration
In C/C++, we declare variables like this:
```C++
The code copy is as follows:
void foo() {}
int a = 0;
char b = 'a';
float c = 1.0f;
void (*d)() = foo; ///< Forgot if that's what I wrote, in short, it's a function pointer
And in Node.js it looks like this:
```javascript
The code copy is as follows:
function foo() {}
var a = 0;
var b = 'a';
var c = 1.0;
var d = foo;
So, no matter what type of variable it is, it is solved with a var in Node.js.
Loop statement
for…i
This loop statement is basically the same as C/C++, both
```C++
The code copy is as follows:
for(int i = 0; i < foo; i++)
{
//...
}
And since Node.js is a weak type, just need:
```javascript
The code copy is as follows:
for(var i = 0; i < foo; i++) {
//...
}
for…in
This is a post-shaped loop statement, similar to PHP's foreach.
For example, we have a JSON object as follows:
javascript
The code copy is as follows:
var foo = {
"hello" : "world",
"node" : "js",
"blahblah" : "bar"
};
At this time, we can use for...in to loop through:
javascript
The code copy is as follows:
for(var key in foo) {
console.log(key + ": " + foo[key]);
}
If we type the following command in the command line:
The code copy is as follows:
$ node foo.js
The following content will be displayed on the screen:
The code copy is as follows:
hello
: world
node: js
blahblah: bar
Tip: From the above, 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 get the key value, you can only get it in the form of foo[<current key name>]. This is still a bit different from PHP foreach.
while…do, do…whill
I won't explain this much, it's no big difference from other languages. It's nothing more than that if there is a variable declaration, it's enough to use var.
Operators
+, -, *, /
This is the case with these operators, one should pay attention to +. It can act on both strings and numerical operations. Although weak-type languages say that types are weak, numbers can sometimes appear in the form of strings, and strings can sometimes appear in the form of numerical values, but when necessary, you still need to talk about what type it is. We can use the following code to see the results:
The code copy 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, which is used to parse a string into a variable of type int.
The above code execution result is:
The code copy is as follows:
12
3
Note: The result of the first console.log is 12. Since a is a string, b is also added as a string by the system. The result is that the two strings are glued together and become 12. The result of the second console.log is 3 because we convert the first a into int type, and add two int type variables, that is, add values, and of course, the result is 3.
==, ==, !=, !==
Here is a point to explain that when the length of this logical operator is 2 (==, !=), it only determines whether the external value is the same, but does not determine the type. like
The code copy is as follows:
var a = 1, b = "1";
console.log(a == b);
The result of its output is true. But if we add an equal sign when we make judgments in the middle, then we will make a strict judgment. It will only be true when the type and value are the same, otherwise it will be false. That is to say
The code copy is as follows:
var a = 1, b = "1";
console.log(a === b);
When , the result returned is false, because a is of int type, while b is a string.
By the way, let’s talk about the conditional statement. In fact, if here is no different from other languages, it is just a problem of two equal signs and three equal signs for several logical operators. So I won't give much tiring statement.
typeof
Here I will regard it as an operator rather than a function.
The function of this operator is to judge the type of a variable, and will return a string, that is, the type name. You will know if you execute the following code:
The code copy is as follows:
function foo() {}
var a = 0;
var b = 'Shh~ Egg flower soup is sleeping. ';
var c = 1.0;
var d = foo;
var e = { "a" : a };
var f = [ 1, 2, 3 ];
var g = null;
var h = undefined;
console.log(typeof a);
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:
The code copy 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. Everyone may be familiar with the first one. There are also C/C++, but it is capitalized, and its essence is one.
```C++
define NULL 0
In JavaScript, the meanings of these three values are different.
### null ###
null is a special object, which roughly means empty. For example:
var a = null;
Everyone can understand it, so I won’t explain it. But unlike C/C++, this null is not equal to 0.
### undefined ###
What this thing means is that this variable is not declared. In order to better distinguish null, our sample code is as follows:
```javascript
The code copy is as follows:
var a = {
"foo" : null
};
console.log(a["foo"]);
console.log(a["bar"]);
In the above code, we make the value of a["foo"] empty, that is, null. And it is not declared at all, it is not even empty. Everyone should have guessed the output results:
The code copy is as follows:
null
undefined
NaN
This is an empty value, a special number. Its full name is Not a Number. It's a bit strange. You can understand it as a number type variable that is not a numeric form, or a number type variable with errors.
It often occurs when floating-point numerical operation errors (such as dividing by 0), or even the user can make a variable equal to NaN by himself to return an error value so that everyone knows that the function has had an error in operation.
Small miscellaneous
The other remaining statements are similar to other existing languages, such as break, switch, continue, etc.
Variable Type
This section mainly talks about JavaScript objects, and other types are almost the same.
Basic Type
The basic types contained in Node.js are almost as follows:
number
string
boolean
array
The first three types can be assigned directly, and the assignment of array is just a reference assignment. If a certain value is changed in a new variable, the value of the old variable will also change. You can directly try the following code:
javascript
var foo = [ 1, 2, 3 ];
var bar = foo;
bar[0] = 3;
console.log(foo);
It results in:
javascript
[ 3, 2, 3 ]
In other words, if an array is copied into a new array, it cannot be used to directly assign values, but must be "deeply copied".
Here we need to talk about the three ways to create array.
The first type:
javascript
The code copy is as follows:
var dog = new Array();
dog[0] = "shh~";
dog[1] = "egg flower soup";
dog[2] = "Sleeping";
The second type:
javascript
The code copy is as follows:
var dog = new Array( "Shh~", "Egg Flower Soup", "Sleeping");
The fourth type:
javascript
The code copy is as follows:
var dog = [
"Shh~",
"Egg Flower Soup",
"Sleeping"
];
I personally prefer the third way of writing, which is relatively concise.
JSON Objects
Here I take out the JSON object separately instead of classifying it as a JavaScript object. If I think I am a little misleading, I can skip this section directly.
My distinction between JSON objects and JavaScript objects is whether it is used to store data only, rather than instantiation of a class. In fact, the essence of JSON is JavaScript Object Notation.
For more information about JSON, please encyclopedia yourself.
Declaring a JSON object in Node.js is very simple:
javascript
The code copy is as follows:
var dog = {
"pre" : "Shh~",
"sub" : {
"name" : "Egg Flower Soup",
"act" : "Sleeping",
"time" : 12
},
"suf" : [ "I said", "It's sleeping", "It's sleeping" ]
};
There are two ways to get the key value of a certain key name in a JSON object. The first is to connect it with dots, and the second is to use brackets:
javascript
The code copy is as follows:
dog
.pre;
dog["pre"];
Note: When using dots above, the key in JSON is directly followed. If you treat the key as a variable, you can only try it with dog[key]: Now you can try it yourself and use for...in to traverse the JSON object above. Don't forget to use typeof ~
The basis of a class (object)
Strictly speaking, the class of Node.js cannot be considered a class. In fact, it is just a collection of functions, adding some member variables. Its essence is actually a function.
However, for the sake of common sense, we will call it "class" next and later, and the instantiated one is called "object".
Because a class has many functions, or its essence is a function, we may talk about the basics of the function when we are not careful.
Declaration and instantiation of classes
Declaring a class is very simple, don't laugh:
javascript
function foo() {
//...
}
OK, we have written a foo class.
True or fake? ! real.
Don't believe it? If you don't believe it, you can type a code and read it:
javascript
var bar = new foo();
Don't look at it as a function, if written in such a form (new), it is an instantiation of this class.
And this so-called foo() is actually the constructor of this foo() class.
Member variables
There are two good ways to get member variables.
The first is to use this.<variable name> in the class constructor or any constructor. You can declare a member variable at any time, and it will not affect the use outside. Anyway, even if you use it when it is not declared, there will be an undefined to support it. So this is the first method:
The code copy is as follows:
javascript
function foo() {
this.hello = "world";
}
Note: This is the member variable of the calling class only when this is added, otherwise it is just a local variable in the function. It is necessary to distinguish whether there is this variable's scope of action.
The second method is to declare it outside the constructor or any member function, and its format is <class name>.prototype.<variable name>:
javascript
The code copy is as follows:
function foo() {
//...
}
foo.prototype.hello = "world";
No matter which of the above method is a declaration of member variables, we can see the effect:
javascript
The code copy is as follows:
var bar = new foo();
console.log(bar.hello);
You can even modify this class like this:
javascript
The code copy is as follows:
function foo() {
this.hello = "world";
}
foo.prototype.hello = "egg flower soup";
Then use the above code to output it.
Think about why the output is world instead of egg soup.
Constructor
We have said before that foo() is actually a constructor. Then obviously we can pass parameters to the constructor, so we have the following code:
javascript
The code copy is as follows:
// Code 2.1
function foo(hello) {
if(hello === undefined) {
this.hello = "world";
} else {
this.hello = hello;
}
}
We see a strange judgment on it if (hello === undefined). What is the use of this judgment? The first possibility is that the developer specially sent an undefined in pain. At this time, it is undefined.
There is another situation. We said from the beginning that JavaScript is a weak-type language. In fact, it is not just a weak-type, but its transmission parameters are also very unrigorous. You can pass more or less (as long as you ensure that the program does not make any errors when you pass more or less or less), it is OK in principle. The parameters of multiple passes will be automatically ignored, while the parameters of few passes will be supplemented with undefined.
Just look at the following code and you will understand:
javascript
The code copy is as follows:
//Connect code 2.1 on
var bar1 = new foo();
var bar2 = new foo("Egg Flower Soup");
Please output two bar hello variables by yourself, and you will find that one is world and the other is egg soup. Obviously, when our first bar1 was declared, it was automatically regarded as by Node.js:
javascript
The code copy is as follows:
var bar1 = new foo(undefined);
So there is a saying that it is world.
Also in this constructor, we see that the parameter passed in is hello, and there is a member variable in this class that is this.hello. However, we have said before that the scope is different when there is this and this is not. That parameter is only used in the constructor, while the one with this is a member variable. Use this to distinguish them immediately, so it doesn't matter even if the same name is.
Member functions
Member function declaration
The declaration of a member function is similar to the second declaration method of a member variable, that is, <class name>.prototype.<function name> = <function>;
javascript
The code copy is as follows:
//Connect code 2.1 on
function setHello(hello) {
this.hello = hello;
}
foo.prototype.setHello = setHello;
bar1.setHello("Egg Cake");
As the above code is obvious, we implement the setHello function of the foo class, through which we can modify the value of foo.hello.
But isn't it a bit troublesome to write like this? Next, I will talk about an important feature of JavaScript functions.
★ Anonymous Functions★
Many times, some of our functions are only referenced or called in one place, so it is too worthwhile to give this function a name, and there is no need, so we can write this function temporarily and directly ask the person who references it to reference it, and the person who calls it to it to call it. Therefore, the function can omit the function name, such as:
javascript
The code copy is as follows:
function(hello) {
this.hello = hello;
}
As for how to quote or call it? If the above class needs to be quoted, it is written like this:
javascript
The code copy is as follows:
foo.prototype.setHello = function(hello) {
this.hello = hello;
}
This writing method is the same as member function declaration, and saves a lot of code. And in fact, basically the declaration of class member functions is declared in this way of anonymous functions.
As for how to make anonymous functions be called? This is usually written like this when passing in a function that is only called by a certain function.
For example, we have a prototype of a function:
javascript
The code copy is as follows:
/**
* We will pass in two variables a and b,
* After calculating the value of a+b, hand it over to func(num)
* Go to output
*/
function sumab(a, b, func) {
var c = a + b;
func(a, b, c);
}
For example, we have two versions of output functions, one is Chinese output and the other is English output. So if we don’t use anonymous functions:
javascript
The code copy is as follows:
function zh(a, b, sum) {
The value of console.log(a + " + " + b + " is: " + sum);
}
function en(a, b, sum) {
console.log(a + " plus " + b + " is " + sum);
}
sumab(1, 2, zh);
sumab(3, 4, en);
Execute this code once, and the output will be:
The value of 1 + 2 is: 3
3 plus 4 is 7
If such code is in the form of anonymous functions, it will be:
javascript
The code copy is as follows:
sumab(1, 2, function(a, b, sum) {
The value of console.log(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. I will introduce it in future chapters.
How to declare anonymous function in member function declaration
Although I have talked about it in the previous section, I will just talk about it again.
Usually, when we declare a class member function, we use anonymous functions to declare it, because anyway, that function is just a member function of this class and will not be referenced or called separately in other places, so the following code is available:
javascript
The code copy is as follows:
//Connect code 2.1 on
foo.prototype.setHello = function(hello) {
this.hello = hello;
}
In this way, we have the function setHello in the foo class.
2.3.4. Class arbitrary
This is my nonsense again. The so-called randomness of classes means that in JavaScript you can modify your class anywhere, which has certain similarities with 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 that some parts of this string are not perfect and want to add our own method, then we can add a function to it where you want, such as:
javascript
The code copy is as follows:
String.prototype.sb = function() {
var newsstr = "";
for(var i = 0; i < this.length; i++) {
if(i % 2 === 0) newsr += "s";
else newsr += "b";
}
return newsr;
};
The meaning of this function is to fill a string to make it into the incarnation of sb.
Let's test it:
The code copy is as follows:
var str = "Shh~ Egg flower soup is sleeping.";
console.log(str.sb());
You will get the following result:
sbsbsbsbsbsbsbs
If you say "Shhh~ Egg Flower Soup is sleeping." Your computer will scold you for being a fool four times and a half. (Smash it quickly)
3. Attached
3.1. Deep copy
The so-called deep copy is to create a new array or object by yourself, and manually copy the basic type variable values in the source array or object one by one, instead of just taking the references to the source array or object. So this involves a recursive call or something.
Below is a deep copy function I implemented. You can write one of your own and add it to your own Node.js knowledge base.
javascript
The code copy 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;
}