1. JS operators (not all, to be added...)
Ordinary operators do not remember, remember some commonly used and often tested.
① ... operator
MDN: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Spread_syntax
Especially easy to use!!! Use it!!!
For example:
function myFun(a,b,c){######} var arr = [1,2,3] myFun(...arr) // The effect is the same as myFun(1,2,3)
var arr1 = [0,1,2]; var arr2 = [3,4,5]; var arr3 = [...arr1, ...arr2] // [0,1,2,3,4,5] effect and Arr1 Concat (arr2) is the same
var obj1 = {a: 'a111', b: 11} var obj2 = {a: 'a222', c: 34} var obj3 = {...obj1, ...obj2} //A after {a:'a222',b:11,c:34} covers the previous a
Arguments in the arguments of the function
It can also be easily converted to a normal array.
function fun(){ let arr = [...arguments] console.log(arr[1]) } fun(2,3,4); // 3
② typeof operator
MDN: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/typeof
typeof determines the type of an object / data.
There are 8 common output results (fast memory: nfusbsbo):
number,function,undefined,string,boolean,symbol,bigint,object
Note: typeof cannot check Array, Set, Map, Date, WeakMap and WeakSet, which are all "object s"
// The console is omitted here log(xxx) typeof 12; // "number" typeof NaN; // "number" function fun01(){}; typeof fun01; //"function" typeof a; // "undefined" typeof ''; // "string" typeof true; // "boolean" typeof Symbol(); // "symbol" typeof 12n; // "bigint" is a new feature in recent years. It represents a large number typeof null;//"object" typeof {};//"object" typeof [];//'object' cannot determine the array
③ in operator
MDN: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/in
prop in object
The left is the attribute of an object, and the right must be an object
The function is to return true if the property on the left is in the object on the right or in the prototype chain of the object
const obj = {a:1,b:2,c:3}; console.log('b' in obj); // true. Note that 'b' in obj; Not b in obj. delete obj.b; // After deletion, it's gone. The following shows false console.log('b' in obj); // false // Array is also OK. The index number is on the left const arr = ['','','',undefined,'']; console.log(0 in arr); // true console.log(3 in arr); // True. Its value is undefined, which is also true console.log(9 in arr); // false delete arr[3]; // After you delete it, you can't find it console.log(3 in arr); // false
Other usage examples:
// The console is omitted here log(xxx) 'PI' in Math; // true let str = new String('strrrrr'); 'toString' in str; // true //The above using new is a string object, and the following writing a string directly is not an object, so an error will be reported let str2 = 'teriri'; 'toString' in str2; // Cannot use 'in' operator to search for 'toString' in teriri
④ async operator
MDN: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/async_function
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/async_function
async and await are used together to replace then then. then.
Then why do you use it? Since js is a single threaded language, the code is easily blocked when running. There is no way but to wait. So js has a concept of multithreading: some important steps really need to run in the single thread of the main thread, but the time-consuming things of loading files can be assigned to other threads, so there is no need to block the main thread. Therefore, it has the concept of asynchrony.
The code in the main thread is executed from top to bottom. In case of asynchronous code, it will be thrown into the branch thread to run. The main thread continues to run. When there are multiple asynchronies in the main thread at the same time, the code in the main thread is generally arranged from top to bottom, which can not control the order of asynchronous results. Generally, which asynchrony runs first will produce results. What if there is order between these asynchronies, and the next asynchrony can only be run after this asynchrony has run a certain result?
Therefore, the sequential execution of asynchrony can be solved by using asynchrony over asynchrony, as shown in the following code:
const fs = require('fs') // 2. Call the method to read the file, native, callback hell! fs.readFile('./resources/engage in study.md', (err, data1)=>{ fs.readFile('./resources/Rice transplanting Poetry.md', (err, data2)=>{ fs.readFile('./resources/Have a sense of reading.md', (err, data3)=>{ let result = `${data1}\r\n${data2}\r\n${data3}` console.log(result) }) }) })
The results are shown in the figure below:
You can read these three poems in order.
However, such code will cause callback hell and poor code readability.
Therefore, the concepts of promise, async and await are introduced to write asynchronous code like synchronous sequential execution.
// Introducing fs module const fs = require('fs') // Call the fs module to read the file function readword(url) { return new Promise((resolve, reject) => { fs.readFile(url, (err, data1)=>{ if(err) reject(err) resolve(data1) }) }) } // Declare an async function async function main() { let weixue = await readword('./resources/engage in study.md') // await is used here to perform these file reading operations in sequence, // It is stipulated that the data of rice transplanting poetry can be read only after reading the data for learning. let chayang = await readword('./resources/Rice transplanting Poetry.md') let guanshu = await readword('./resources/Have a sense of reading.md') console.log(weixue.toString()) // If toString is not used, the byte stream will be output < buffer 20 E4 B8 Ba E5 ad A6 such console.log(chayang.toString()) console.log(guanshu.toString()) } main()
The results are as follows:
Note:
With async function, the return value must be a Promise object. If you return a non Promise type data, you will implicitly give the package a Promise and then return it:
async function foo() { return 'okkkk' // return function(a,b){return a+b} / / see the picture below for the result } console.log(foo()) // Promise {<fulfilled>: "okkkk"}
return function result picture:
Of course, if you return Promise directly, you won't give the package. What is it
async function foo() { return new Promise((resolve, reject) => { resolve('OK'); // Promise {<fulfilled>: "OK"} //reject('Error'); // Promise {< rejected >: "error"} at the same time, the console reports an error }); } console.log(foo()) // See the comments in the above lines for the results
Note:
Await usage: [return value] = await expression;
The await expression pauses the execution of the current async function and waits for Promise processing to complete. If Promise is processed normally (fully), the resolve function parameter of its callback is used as the value of await expression to continue to execute async function. If Promise handles the rejected exception, the await expression will throw the reason for the Promise exception.
In addition, if the value of the expression after the await operator is not a Promise, the value itself is returned.
If the expression after await returns Promise, it will be implicitly parsed. If it is not Promise, it will be output directly.
For example:
async function foo() { let a = await new Promise(resolve => { setTimeout(() => { resolve('teriri okk'); }, 0); }); console.log(a); // After foo() runs, the console outputs' teriri okk ', indicating that the assigned value of a is the value of promise parsed by await } foo()
async function foo() { let a = await 'okk' console.log(a) // After foo() runs, the console outputs' okk ' } foo()