Introduction
This article mainly introduces the basic syntax of js and ts to facilitate front-end development.
JavaScript
More detailed JavaScript learning materials: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript
Introduction
Positioning : JavaScript is a dynamic language that contains types, operators, standard built-in objects and methods. In terms of basic syntax, JavaScript has many similarities with C/C++ and is often used in browser development.
Dependent on the host : Unlike most programming languages, JavaScript has no concept of input or output. It is a script language that runs in a host environment. Any mechanism for communicating with the outside world is provided by the host environment. The browser is the most common hosting environment, but JavaScript interpreters are also included in many other programs, such as Adobe Acrobat, Adobe Photoshop, SVG images, Yahoo!'s Widget engine, and server-side environments such as Node.js.
Standards : We sometimes see names like ECMAScript or ES6. ECMA is the standardization organization for JavaScript. ECMAScript is a standard for the JavaScript language. The reason why it is not called JavaScript is because the trademarks of Java and JavaScript have been registered. . Therefore, the relationship between ECMAScript and JavaScript is that the former is a specification of the latter, and the latter is an implementation of the former (other ECMAScript dialects include JScript and ActionScript)
Operating environment
Install the js interpreter node.js, enter npm -v in the terminal to check whether the installation is successful.
Install the vscode plug-in code runner to facilitate running js code
Then you can ctrl+alt+N or click the triangle icon at the top to run the js code. In addition, js can also be run directly with F5.
console.log("Hello World")
or terminal input
node js/learn.js
type of data
-
Number
(number)- 3/2=1.5 (default floating point operation)
- The special value
NaN
(short for Not a Number) ifNaN
any mathematical operation is performed with as an argument, the result will also beNaN
.NaN
Comparisons with==
,!=
,===
, and!==
any other value will not be equal - including comparisons with other NAN values. Must useNumber.isNaN()
orisNaN()
function - Built-in objects
Math
support some advanced calculations;
-
String
(string)-
Coding specification: A string in JavaScript is a sequence of Unicode characters
-
Statement:
'
Both"
are acceptable -
Conversion: You can use the built-in function
parseInt()
andparseFloat()
to convert a string to a number -
Placeholder
let name = "Bob", time = "today"; console.log(`Hello ${ name}, how are you ${ time}?`); let a = 5; let b = 10; console.log(`Fifteen is ${ a + b} and not ${ 2 * a + b}.`);
-
-
Boolean
(Boolean) -
Symbol
(symbol) (new in ES2015) -
Object
(object)
-
Function
(function) -
Array
(array)-
The length and element type of JavaScript arrays are non-fixed, and their data can also be discontinuous in memory.
-
Allow undefine this kind of data
-
Similar to the String above, you can
new Array()
create an array. Of course, it is easier to use literals to create itlet a =['abc',1];
. -
let a = [1, 2, , 4]; console.log(a[2]); a[100] = 100; a.pop(); console.log(a.length);
-
-
Date
(date) -
RegExp
(regular expression)
-
-
null
(null) -
undefined
(undefined)
You can see that functions and arrays also belong to objects
variable
statement
JavaScript has three ways of declaring variables.
-
Declare a global or function scope variable, optionally initializing a value.
-
Declare a block-scoped local variable, optionally initializing a value.
-
Declare a block-scoped read-only constant that must be initialized to a value.
If a variable is declared but not assigned a value, the variable's type isundefined
const
It is obviously a constant, and it is read-only. The main difference between let
and is that the scope of is the block scope, while the scope of is the global or function scope ( also a block scope), and there is no variable promotion.var
let
var
const
let
variable promotion
That is, if the variable is used before it is declared, an error will be reported under normal circumstances, but variable promotion is equivalent to declaring undefined in advance.
It is easier to debug hidden errors using let, because if it is not declared in advance, an error will be reported directly, as shown in the following code
// var 的情况
console.log(foo); // 输出undefined
var foo = 2;
// let 的情况
console.log(bar); // 报错ReferenceError
let bar = 2;
Their detailed differences can be found here
Expand syntax
Spread syntax allows us to quickly use an existing array to construct a new array
let a = [1, 2, 3];
let b = {
1: "1", 2: "2" };
let c = [...a, 4];
//[1, 2, 3, 4]
let d = {
...b, 3: "3" };
//{1: "1", 2: "2", 3: "3"}
operator
Here we only introduce the parts that are different from C++
-
Exponentiation:
x**2
-
Congruence and Inequality:
x===y
x!==y
Compare whether two operands are equal and of the same type -
Unary positive: i.e.
+
if the operand was not a number before, try to convert it to a number -
String operations:
+
You can directly concatenate two strings, and at the same time try to convert the other operand to a string -
Destructuring assignment : Take attributes/values out of objects/arrays and assign them to other variables, such as
var a, b, rest; [a, b, ...rest] = [10, 20, 30, 40, 50]; console.log(a); // 10 console.log(b); // 20 console.log(rest); // [30, 40, 50] var o = { p: 42, q: true }; var { p, q } = o;
control structure
The control structure of JavaScript is similar to that of other C-like languages, and is listed here.
branch
if
//分支
var name = "kittens";
if (name == "puppies") {
name += "!";
} else if (name == "kittens") {
name += "!!";
} else {
name = "!" + name;
}
name == "kittens!!"; // true
switch
switch (action) {
case "draw":
drawIt();
break;
case "eat":
eatIt();
break;
default:
doNothing();
}
cycle
while
while (true) {
}
do … while
var input;
do {
input = get_input();
} while (inputIsNotValid(input));
for
for (var i = 0; i < 5; i++) {
}
unique
JavaScript also includes two other important for loops:
for (let value of array) {
// do something with value
}
for
…in
:
for (let property in object) {
// do something with object property
}
for ... in
is built for iterating over object properties and is not recommended for use with arrays
function
definition
function add(x, y) {
var total = x + y;
return total;
}
parameter
Not enough: Missing parameters will be undefined
replaced by
Too many: Too many parameters will exist arguments
in this internal object, which can be accessed like an array, as follows
function add() {
var sum = 0;
for (var i = 0, j = arguments.length; i < j; i++) {
sum += arguments[i];
}
return sum;
}
add(2, 3, 4, 5); // 14
Multi-parameter improvement: Because arguments
it is ugly and long to write, we can use the remaining parameters to achieve similar functions, as follows
function avg(first, ...args) {
var sum = first;
for (let value of args) {
sum += value;
}
return sum / args.length;
}
avg(2, 3, 4, 5); // 3.5
Nested functions
JavaScript also allows functions to be defined inside a function, and they can access variables in the scope of the parent function
function parentFunc() {
var a = 1;
function nestedFunc() {
var b = 4; // parentFunc 无法访问 b
return a + b;
}
return nestedFunc(); // 5
}
anonymous function
It is convenient for us to implement some short functions
//直接调用
(function (x, y) {
return x + y;
})(1, 2);
//3
//作为参数传递
setTimeout(function () {
console.log("111");
}, 1000);
//赋值给变量
const add = function (x, y) {
return x + y;
};
add(1, 2);
//3
arrow function
Allows us to define functions in a simpler way instead of using functions all the time, often used for anonymous functions
(param1, param2, …, paramN) => {
statements }
(param1, param2, …, paramN) => expression
//相当于:(param1, param2, …, paramN) =>{ return expression; }
// 当只有一个参数时,圆括号是可选的:
(singleParam) => {
statements }
singleParam => {
statements }
// 没有参数的函数应该写成一对圆括号。
() => {
statements }
object
The object in JavaScript can be simply understood as a "name-value" pair
Generally defined as follows
//创建
let person = {
};
//添加
person.name = "John";
person.age = 30;
person.isStudent = false;
//删除
delete person.age;
//修改
person.name = "Tom";
//访问
console.log(person.name);
console.log(person['name']);
member function
let person = {
name: "Alice",
age: 25,
sayHello: function() {
console.log("Hello, my name is " + this.name);//使用this访问
}
};
person.sayHello();
The details about OOP will not be introduced here. Its concepts are somewhat similar to C++. If you want to review OOP and understand the objects in Js, you can refer to here.
asynchronous
When we execute the code, we will encounter the function that loads resources, which will block the running of our program.
But in order to make full use of our computer, because it can handle multiple tasks at the same time, let this blocking operation be performed in the background, and the ontology code continues to execute
This situation of executing multiple functions at the same time is called asynchronous. There are several ways to implement asynchronous, each with its own advantages and disadvantages.
Callback
Definition: Callbacks are passed as parameters to other functions that are executed in the background.
Function: When the code running in the background ends, the callbacks function is called to notify you that the work has been completed, so you can use the callback function to achieve asynchronous
Since we rarely use callbacks to implement asynchronously later (this way of writing is relatively old and has some shortcomings)
Here is a simple example using setTimeout
to simulate a blocking function
setTimeout(() => {
console.log("hi");
}, 2000);
console.log("bye");
Regarding callback functions, there is another interesting callback hell situation that will occur, that is, as the amount of code increases, the readability of the code will be very poor, as shown below
If you need to process a pizza order, first perform toppings to select the pizza type, then order to generate the order, and then start making pizza.
Because each execution requires waiting time, it is implemented asynchronously.
chooseToppings(function (toppings) {
placeOrder(
toppings,
function (order) {
collectOrder(
order,
function (pizza) {
cookPizza(pizza);
},
failureCallback
);
},
failureCallback
);
}, failureCallback);
Promise
Witnessed the above callback hell, so I came up with promise to solve this problem.
fetch("products.json")
.then(function (response) {
return response.json();
})
.then(function (json) {
products = json;
initialize();
})
.catch(function (err) {
console.log("Fetch problem: " + err.message);
});
Here fetch()
returns a promise . It is an object indicating the completion or failure of the asynchronous operation. It can be said that it represents an intermediate state. Essentially, this is the browser's way of saying "I promise to get back to you as soon as possible", hence the name "promise". In the above code, what follows the promise is
- Two
then()
blocks. Both contain a callback function that will be run if the previous operation was successful, and each callback receives the result of the previous successful operation as input so other operations can continue to be performed on it. Each.then()
block returns another promise, which means that multiple blocks can be.then()
chained to another block, so that multiple asynchronous operations can be performed one after another. - If any of
then()
the blocks fails, the block is run at the end - similarcatch()
to synchronization , an error object is provided that can be used to report the type of error that occurred.try...catch
catch()
The Promise object essentially represents the intermediate state of a series of operations, or the result returned after an operation completes or fails at a certain time in the future. Promise does not guarantee when the operation will be completed and the result will be returned, but it does guarantee that your processing code for the operation result will be executed after the current operation succeeds, or that the operation failure will be handled gracefully after the operation fails.
For the pizza order above, using Promise we can implement it elegantly like this
chooseToppings()
.then((toppings) => placeOrder(toppings))
.then((order) => collectOrder(order))
.then((pizza) => cookPizza(pizza))
.catch(failureCallback);
async await
async
and await
are syntactic sugar for promises added in ECMAScript 2017, making asynchronous code easier to write and subsequently read.
Add async and await directly in front of the function to be executed
Using async and await will make your code look more like synchronous code, and it is also very easy to understand, because it is actually executed sequentially, but it will not block while waiting for await, affecting other rendering tasks.
The following is a comparison of promise and async
Promise
fetch("coffee.jpg")
.then((response) => response.blob())
.then((myBlob) => {
let objectURL = URL.createObjectURL(myBlob);
let image = document.createElement("img");
image.src = objectURL;
document.body.appendChild(image);
})
.catch((e) => {
console.log(
"There has been a problem with your fetch operation: " + e.message
);
});
async await
async function myFetch() {
try {
let response = await fetch("coffee.jpg");
let myBlob = await response.blob();
let objectURL = URL.createObjectURL(myBlob);
let image = document.createElement("img");
image.src = objectURL;
document.body.appendChild(image);
} catch (e) {
console.log(e);
}
}
myFetch();
Modular
ECMAScript module | Node.js v20 documentation (nodejs.cn)
The following is the import/export method
import transform from './transform.js' /* default import */
import {
var1 } from './consts.js' /* import a specific item */
import('http://example.com/example-module.js').then(() => {
console.log('loaded')})
export const MODE = 'production' /* exported const */
TypeScript
Introduction
An open source programming language developed by Microsoft. It is a superset of JavaScript. The runtime compiler converts it into JavaScript code, which is then executed by the js engine.
The essential difference: A type system is added to make the code easier to statically analyze, while supporting a wider range of object-oriented
For more in-depth study, please refer to the official documentation ( Chinese ). Here we will give a brief introduction.
Operating environment
js installation running environment, you also need to use npm (Node Package Manager) to install the following two packages, enter the following commands in the terminal to configure the running environment
npm install -g ts-node
npm install -g typescript
Then you can press ctrl+alt+n to run the ts code
const first: string = "Hello World";
console.log(first);
Or enter directly into the terminal
ts-node ts/learn.ts#注意cd到工作目录
type annotation
Use directly: to mark the type
common
//布尔值
let isDone: boolean = false;
//数字
let decLiteral: number = 6;
let hexLiteral: number = 0xf00d;
let binaryLiteral: number = 0b1010;
let octalLiteral: number = 0o744;
//字符串
let name: string = "bob";
name = "smith";
let sentence: string = `Hello, my name is ${
name}.`;
//数组
let list: number[] = [1, 2, 3];
let list: Array<number> = [1, 2, 3];
//元组,表示一个已知元素数量和类型的数组,各元素的类型不必相同
// Declare a tuple type
let x: [string, number];
// Initialize it
x = ["hello", 10]; // OK
// Initialize it incorrectly
x = [10, "hello"]; // Error
//枚举
enum Color {
Red,
Green,
Blue,
}
let c: Color = Color.Green;
//Void,表示一个函数没有返回值
function warnUser(): void {
console.log("This is my warning message");
}
//Null 和 Undefined
let u: undefined = undefined;
let n: null = null;
//他们是所有类型的子类型
// 这样不会报错
let num: number = undefined;
any
It is the type of native js. If there is no declared type, it will default to any to make it compatible with js.
It is also used to specify a type for variables whose type is not clear at the programming stage, such as content from user input or third-party code libraries.
The following is an example of specifying a function type:
// 完整,这里详细描述了函数类型
let myAdd: (x: number, y: number) => number = function (
x: number,
y: number
): number {
return x + y;
};
//推断前面
let myAdd = function (x: number, y: number): number {
return x + y;
};
//推断后面,这种写法比较喜欢
let myAdd: (x: number, y: number) => number = function (x, y) {
return x + y;
};
console.log(myAdd(1, 2))
ts can also set optional parameters and parameter default values. Optional parameters can be added with ? after the parameters.
let myAdd = function(x: number = 1, y?: number): number {
...};
union type
Union Types indicate that the value can be one of multiple types. Union types use |
separate each type.
let myFavoriteNumber: string | number;
myFavoriteNumber = "seven";
myFavoriteNumber = 7;
When TypeScript is not sure what type a variable of a union type is, we can only access the properties or methods common to all types of this union type , as follows, and the type will not be determined based on the access method.
In this case we can use type assertions
function getLength(something: string | number): number {
return something.length;
}
//index.ts(2,22): error TS2339: Property 'length' does not exist on type 'string | number'.
// Property 'length' does not exist on type 'number'.
type assertion
When we know what type our data is
The two ways of type assertion are
let someValue: any = "hello world";
let strLength0: number = (someValue).length;
let strLength1: number = (<string>someValue).length;
let strLength2: number = (someValue as string).length;
console.log(strLength0);
type alias
We use to type
create type aliases, that is, custom types, often used for union types
type Name = string;
type NameResolver = () => string;
type NameOrResolver = Name | NameResolver;
interface
similar to struct
interface Person {
name: string;
age?: number;//这里为可选类型
}
let tom: Person = {
name: "Tom",
age: 25,
};
let jack: Person = {
name: "Jack",
};
Generics
This concept is similar to templates in C/C++. Since I am learning basics, I don’t understand it in detail.
template <typename T>
function identity<T>(arg: T): T {
return arg;
}
let myIdentity: <T>(arg: T) => T = identity;
module
Any declaration (such as a variable, function, class, type alias or interface, regular expression) can be export
exported by adding keywords.
Can be exported directly when declaring
export interface StringValidator {
isAcceptable(s: string): boolean;
}
export const numberRegexp = /^[0-9]+$/;
export class ZipCodeValidator implements StringValidator {
isAcceptable(s: string) {
return s.length === 5 && numberRegexp.test(s);
}
}
Can also be exported anywhere after declaration and can be renamed
class ZipCodeValidator implements StringValidator {
isAcceptable(s: string) {
return s.length === 5 && numberRegexp.test(s);
}
}
export {
ZipCodeValidator };
export {
ZipCodeValidator as mainValidator };
When importing, you can import it directly or rename it.
import {
ZipCodeValidator } from "./ZipCodeValidator";
import {
ZipCodeValidator as ZCV } from "./ZipCodeValidator";
Each module can have an default
export. Default exports are default
marked with keywords; and a module can only have one default
export. There is no need to add braces when default
importing modules, and they can be renamed directly.
//OneTwoThree.ts
export default "123";
import
import num from "./OneTwoThree";
Babel
Introduction
Official documentation Babel Chinese website
Babel is a widely used JavaScript compiler. Its main function is to convert high-version JavaScript code (usually ECMAScript 2015+ standard) into backward-compatible low-version JavaScript code to ensure correct execution in various browsers and environments.
Specifically, Babel can perform the following tasks:
- Convert ES6+ code to ES5 code: Babel is most commonly used to convert code written using the latest JavaScript standards (such as arrow functions, template strings, destructuring assignment, etc.) to older versions of JavaScript to ensure that browsers that do not support the latest standards It can also run normally in the device.
- Handling JSX: Babel can also handle JSX syntax, converting it into React.createElement calls for use with React in environments that do not support JSX.
- Plugin support: Babel is highly extensible, allowing users to customize the conversion process through plugins. This means you can add or remove transformation rules based on your project's needs.
- Compile other languages to JavaScript: Babel’s ecosystem also supports compiling other languages (such as TypeScript, Flow, etc.) to JavaScript.
One of the main advantages of using Babel is that it enables developers to use the latest JavaScript syntax and features without worrying about compatibility issues in the target environment. Developers can write code with clear, modern syntax, and Babel takes care of converting it into a more widely supported version of JavaScript.
use
First of all, babel does not provide conversion. It uses different plug-ins to convert different syntaxes.
Plug-ins are divided into grammar plug-ins and translation plug-ins. Because generally translation plug-ins include corresponding grammar plug-ins, grammar plug-ins are rarely used directly.
basic
Install
yarn add --dev @babel/core @babel/cli #前者是核心库,后者是用命令行操控babel
use
./node_modules/.bin/babel src --out-dir lib
#将当前目录src文件夹的js代码转换,也可以写成
npx babel src --out-dir lib
plug-in
Adding a plug-in is a two-step process,
- First add the plugin name to the configuration file (create .babelrc or babel.package.json in the root directory and add the plugin field)
npm install babel-plugin-xxx
Install using
preset
Because there are many new features in a standard, it is troublesome to add them one by one, so we can use the preset combination that babel has premade for us, such as the following preset with ES6+preset-env
We can do this by installing the preset first and then adding it to the configuration file
yarn add --dev @babel/preset-env
{
"presets": [
"preset1",
"preset2",
["preset3", {
options}]
]
}
Convert TS to JS
Installation package
yarn add @babel/core @babel/cli @babel/preset-env @babel/preset-typescript @babel/node --dev
# @babel/core是Babel的核心库
# @babel/cli是Babel的命令行工具
# @babel/preset-env是一组将最新JavaScript语法转化的预设插件集
# @babel/preset-typescript是一组将TypeScript语法转化的预设插件集
# @babel/node可以应用所选的Babel工具并像node一样运行代码
Modify configuration file
{
"presets": [
"@babel/preset-env",
"@babel/preset-typescript"
]
}
Convert
npx babel src -d lib # -d是--out-dir的缩写