Home >Web Front-end >JS Tutorial >NodeJs basic syntax and types_node.js
is written in front
Today I want to check the knowledge about the type of Node. I want to summarize it. I saw an article on Googol, but the original link is no longer there. Pull this article out in the snapshot. If the original author has any questions , please contact me!
This article is all about the basics of JS, experts will automatically skip it! I haven't written much about js before, and I'm relatively weak in this area, so I also encountered trouble when writing node. I'll add some knowledge to myself here!
Text
Node.js is based on the JavaScript scripting language. A common feature of most scripting languages is "weak typing".
Different from PHP, PHP does not need to declare a new variable even if it has a new variable, while JavaScript still needs var to declare it. And this var covers the meaning of all types such as int, string, char, etc. in C, even functions.
All the contents of this and the following articles are edited using vim under Linux or Cygwin (if not, please convert it to your own method), and then view the results on the command line.
Basic Grammar
Variable declaration
In C/C, we declare variables like this:
```C
And in Node.js it looks like this:
```javascript
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 are
```C
Since Node.js is weakly typed, you only need:
```javascript
This is a post-typed loop statement, similar to PHP’s foreach.
For example, we have a JSON object as follows:
javascript
At this time we can use for...in to loop through:
javascript
If we enter the following command on the command line:
The following content will be displayed on the screen:
Tips: As you can see from the above, the for...in statement is used to traverse the key names of JSON objects, arrays, and objects, but does not provide key value traversal. If you want to get the key value, you can only get it in the form of foo[ while…do, do…whill I won’t explain this much. It’s not much different from other languages. It’s just that if there is a variable declaration, you need to use var. Operator , -, *, / That’s it for these operators. What you need to pay attention to is . It can operate on both strings and numeric operations. Although weakly typed languages say that the type is weak, numbers can sometimes appear in the form of strings, and strings can sometimes appear in the form of numeric values. However, when necessary, we still have to say what type it is. We can Use the following code to see the result: The parseInt here is a built-in function of Node.js, which is used to parse a string into a variable of type int. The execution result of the above code is: Note: The first console.log result is 12. Since a is a string, b is also added by the system as a string. The result is that the two strings are glued together and become 12. The second console.log result is 3 because we converted the first a to int type. The addition of two int type variables is the sum of values. The result is of course 3. ==, ===, !=, !== One thing to explain here is that when the length of this logical operator is 2 (==, !=), it only determines whether the external values are the same, but does not determine the type. Such as The result it outputs is true . But if we add an equal sign in the middle of the judgment, then it will be a strict judgment. Only when the type and value are the same will it be true, otherwise it will be false. That is to say , the returned result is false, because a is of int type and b is a string. Let’s talk about conditional statements by the way. In fact, if here is no different from other languages. It is just a matter of several logical operators, two equal signs and three equal signs. So I won’t go into too much detail. typeof Here I will treat it as an operator rather than a function. The function of this operator is to determine the type of a variable. It will return a string, that is, the type name. You can know it by executing the following code: The execution result here will be: null, undefined, NaN In JavaScript, there are three special values, as shown in the title. The first one may be familiar to everyone. It is also found in C/C, but it is capitalized. Its essence is a ```C define NULL 0 In JavaScript, these three values have different meanings. ### null ### null is a special kind of object, which roughly means empty. For example: var a = null; ### undefined ### This thing means that this variable is not declared. In order to better distinguish null, our sample code is as follows: ```javascript In the above code, we make the value of a["foo"] empty, that is, null. And there is no declaration of a["bar"] at all, it is not even empty. Everyone should have guessed the output result: 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 in digital form or has an incorrect value. Mostly occurs when floating-point numerical operation errors (such as division by 0) occur. It can even be the user himself making a variable equal to NaN in order to return an error value to let everyone know that this function operation has gone wrong. Little offal 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 will be almost passed over. Basic Type Node.js contains almost the following basic types: number javascript javascript It is necessary to talk about the three creation methods of array. First type: javascript Second type: javascript javascript I personally prefer the third way of writing, which is more concise. JSON object Here I separate the JSON object instead of classifying it as a JavaScript object. If you feel that I am a bit misleading, you can skip this section directly. My distinction between JSON objects and JavaScript objects lies in whether they are only used to store data, rather than instantiating 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 There are two ways to get the key value of a certain key name in the JSON object. The first is to use dot connection, and the second is to use square brackets: javascript Note: When using dot above, it is directly followed by the key in JSON. If you treat the key as a variable, you can only try it with dog[key]: Now you can try it yourself, use The for...in form traverses the above JSON object. Don’t forget to use typeof meow~ Basics of classes (objects) Strictly speaking, a Node.js class cannot be regarded as a class. In fact, it is just a collection of functions with some member variables. Its essence is actually a function. But for the sake of simplicity, we will refer to it as "class" and the instantiation as "object" in the following and future. Because a class has many function characteristics, or its essence is a function, we may accidentally explain the basics of functions here. Declaration and instantiation of classes Declaring a class is very simple, don’t laugh: javascript Real or fake? ! real. Don’t believe it? If you don’t believe it, you can type a piece of code and take a look: javascript And this so-called foo() is actually the constructor of the foo() class. Member variables There are two ways to use member variables. The first is to use this. Note: Only when this is added, it is a member variable of the calling class, otherwise it is just a local variable within the function. It is necessary to distinguish the scope of the variable when there is no this. The second method is to declare it outside the constructor or any member function. The format is javascript No matter which method above is a declaration of member variables, we can see the effect: javascript You can even modify this class like this: javascript Then use the above code to output. Think about why the output is still world instead of egg drop soup. Constructor We said before that foo() is actually a constructor. So obviously we can pass parameters to the constructor, so we have the following code: javascript We see a strange judgment above if(hello === undefined). What is the use of this judgment? The first possibility is that the developer went out of his way to pass undefined in. At this time, it is understandable that it is undefined. There is another situation. We said at the beginning that JavaScript is a weakly typed language. In fact, it is not only weakly typed, but its parameter passing is also very loose. You can pass more or less (as long as you can ensure that the program does not make errors or the logic does not make errors when you pass more or less), in principle it is okay. Parameters passed in more will be automatically ignored, while parameters passed in less will be complemented with undefined. Look at the following code to understand: javascript Please output the hello variables of the two bars by yourself, and you will find that one is world and the other is egg drop soup. Obviously, when our first bar1 is declared, Node.js automatically sees it as: javascript 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 called this.hello. However, we have said before that the scope is different when there is this and without this. The parameter only acts in the constructor, and the one with this is a member variable. Using this immediately distinguishes them, 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 the second declaration method of member variables, that is, javascript The above code is obvious. We have implemented the setHello function of the foo class, which can modify the value of foo.hello. But isn’t it a bit troublesome to write like this? Next I am going to talk about an important feature of JavaScript functions. ★ Anonymous function ★ Many times some of our functions are only referenced or called in one place, so it is not worthwhile and unnecessary for us to give this function a name, so we can temporarily write this function and directly let the person who refers to it People quote it, people who call it call it. Therefore, the function name can be omitted, such as: javascript As for how to quote or call? If the above class needs to be referenced, it would be written like this: javascript This way of writing has the same effect as member function declaration, and saves a lot of code. And in fact, basically the declaration of class member functions is declared in this anonymous function way. As for how to make the anonymous function be called? This is usually used when passing in a function that is only called by a certain function. For example, we have a function whose prototype is: javascript For example, we have two versions of the output function, one is Chinese output and the other is English output, then if the anonymous function is not used, it is written like this: javascript Execute this code once, the output result will be: The value of 1 2 is: 3 javascript This form is usually used for callback functions. The callback mechanism is the essence of Node.js or JavaScript. It will be introduced in future chapters. Anonymous function declaration method of member function declaration Although I mentioned it in the previous section, let’s talk about it again. Usually when we declare member functions of a class, we use anonymous functions to declare them, because that function is just a member function of this class anyway and will not be referenced or called separately from other places, so there is the following Code: javascript In this way, we make the foo class have the setHello function. 2.3.4. Arbitrariness of classes This is nonsense from me again. The so-called arbitrariness of classes means that you can modify your class anywhere in JavaScript, 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 in case we feel that this string is imperfect in some places and want to add our own method, then we can add a function to it where you want, such as: javascript The meaning of this function is to fill a string so that it becomes the incarnation of sb. Let’s test it out: You will get this result: sbsbsbsbs 3. Attached 3.1. Deep copy The so-called deep copy means 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 reference of the source array or object. So this involves a recursive call or something. The following is a deep copy function I implemented. You can write your own and add it to your own Node.js knowledge base. javascript
var a = "1";
var b = 2;
console.log(a b);
console.log(parseInt(a) b);
12
3
var a = 1, b = "1";
console.log(a == b);
var a = 1, b = "1";
console.log(a === b);
function foo() {}
var a = 0;
var b = 'Shh~ Egg Drop 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);
number
string
number
function
object
object
object
undefined
Everyone can understand it, so I won’t explain it too much. But unlike C/C, this null is not equal to 0.
var a = {
"foo" : null
};
console.log(a["foo"]);
console.log(a["bar"]);
null
undefined
string
boolean
array
Among them, the first three types can be directly assigned, and the assignment of array is just a reference assignment. If a value is changed in the new variable, the value of the old variable will also change. You can directly try the following code:
var foo = [ 1, 2, 3 ];
var bar = foo;
bar[0] = 3;
console.log(foo);
The result it gets is:
[ 3, 2, 3 ]
In other words, if array copies a new array, it cannot use direct assignment, but must "deep copy".
var dog = new Array();
dog[0] = "Shh~";
dog[1] = "Egg Drop Soup";
dog[2] = "Sleeping";
var dog = new Array( "Shh~", "Egg Drop Soup", "Sleeping" );
The fourth type:
var dog = [
"Shh~",
"Egg drop soup",
"Sleeping"
];
var dog = {
"pre" : "Shh~",
"sub" : {
"name" : "Egg Drop Soup",
"act" : "sleeping",
"time" : 12
},
"suf" : [ "I said", "It's sleeping", "It's just sleeping" ]
};
dog
.pre;
dog["pre"];
function foo() {
//...
}
Okay, we've written a foo class.
var bar = new foo();
Regardless of whether it is a function, if it is written in this form (new), it is an instantiation of this class.
javascript
function foo() {
This.hello = "world";
}
function foo() {
//...
}
foo.prototype.hello = "world";
var bar = new foo();
console.log(bar.hello);
function foo() {
This.hello = "world";
}
foo.prototype.hello = "Egg Drop Soup";
// Code 2.1
function foo(hello) {
If(hello === undefined) {
This.hello = "world";
} else {
This.hello = hello;
}
}
// Continued from code 2.1
var bar1 = new foo();
var bar2 = new foo("Egg Drop Soup");
var bar1 = new foo(undefined);
// Continued from code 2.1
function setHello(hello) {
this.hello = hello;
}
foo.prototype.setHello = setHello;
bar1.setHello("Egg Pancake");
function(hello) {
This.hello = hello;
}
foo.prototype.setHello = function(hello) {
This.hello = hello;
}
/**
* 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);
}
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);
3 plus 4 is 7
If such code is in the form of an anonymous function, it will be:
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);
});
// Continued from code 2.1
foo.prototype.setHello = function(hello) {
This.hello = hello;
}
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;
};
var str = "Shh~ Egg Drop Soup is sleeping.";
console.log(str.sb());
If you tell your computer "Shh~ Egg Drop Soup is sleeping.", your computer will call you an idiot four and a half times. (Smash it quickly)
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;
}