The sixth day of self-study JavaScript - some useful js shortcut operations: optional chaining operator, null value merging operator, null value assignment operator, non-null assertion operator, expansion and remainder operator, destructuring
js has some very convenient shortcut operators, similar to ternary expressions. If used well, it can simplify the code very conveniently.
Optional chaining operator ( ?.
)
Read the value of a property located deep in the connection object chain without explicitly verifying that each reference in the chain is valid. If a reference is invalid ( null
or undefined
) does not cause an error but is returned undefined
.
const a = {
id:1, name:'张三'};
console.log(a?.age);
// 多个可选链
let res = a?.name?.firstName;
// 可选链表达式
let res = a?.['na' + 'me'];
// 访问数组
let arrItem = arr?.[13];
It will simplify the judgment of whether the object contains a certain member and if it contains certain properties or methods that access the member.
Null value coalescing operator ( ??
)
The null value coalescing operator is a logical operator that returns its right operand when the left operand is null
or undefined
, otherwise it returns the left operand. It is similar to the logical OR operator, but in some cases (for example, the value on the left ''
is an empty string, or the number 0, or the Boolean value false), the right operand will be returned unexpectedly. The null value coalescing operator only returns the right side if the left side is empty ( null
or ).undefined
let a = 0 || 123; // 123
let a = 0 ?? 123; // 0
let a = false ?? 123; // false
This will simplify certain judgments that may need to be combined with 0 or false, etc., to reduce surprises. It can also be used with optional chaining to return the default value when the accessed attribute is empty.
let a = person?.name ?? '匿名';
null assignment operator ( ??=
)
Similar to the null value coalescing operator, when the left side of the operator is null ( null
or undefined
), the right side is assigned to the left side
let b = 'hello';
let a = 0;
let c = null;
a ??= b; // a === 0
c ??= b; // c === 'hello'
non-null assertion operator ( !.
)
This is the syntax of TypeScript , called non-null assertion operator** (non-null assertion operator)**. Contrary to ?., this symbol indicates that the property behind the object must not be null or undefined.
let a = {
id:1, name='张三'};
console.log(a!.id)
Expansion and remainder operators ( ...
)
In js, the spread operator (spread) and the remainder operator (rest) are both three dots ( ...
)**.
Extended operations
The main function of the expansion operation is to split an array or object into multiple parameter sequences, and it will call the default Iterator
interface
// 扩展数组
const test = (a, b, c) => {
console.log(a) // 1
console.log(b) // 2
console.log(c) // 3
}
let arr = [1, 2, 3];
test(...arr);
// 将一个数组扩展到另一个数组中
let arr1 = [1, 2, 3];
let arr2 = [...arr1, 4, 5]; // [1, 2, 3, 4, 5]
let arr3 = [4, ...arr1, 5]; // [4, 1, 2, 3, 5]
// 将字符串扩展为数组
let str = 'hello';
let arr4 = [...str]; // ['h', 'e', 'l', 'l', 'o']
Extension operations also work on objects
let a = {
id:1, name='张三'};
let b = {
...a};
There is a difference between using object extension and direct assignment. Direct assignment actually assigns the memory address reference of the original object, while extension creates a new object to some extent. It should be noted that expansion is not completely equivalent to deep copying, because expansion only copies the first-level attributes. If there is an object in it, the memory address reference of the object is still assigned.
remainder operation
The remainder operation is just the opposite of the expansion operation. It combines a sequence of values into an array.
// 当函数参数个数不固定,可以使用剩余运算合并成一个数组
const f1 = (...args) => {
console.log(args) // [1, 2, 3]
}
f1(1, 2, 3);
// 部分参数不固定
const f2 = (item, ...args) => {
console.log(item) // 1
console.log(args) // [2, 3]
}
f2(1, 2, 3);
deconstruct
Destructuring is also called unpacking, which is to split an object (or array, because arrays in js are also objects).
Array destructuring
let arr = [1, 2, 3];
// 将数组元素依次赋值给单个变量
let [a, b, c] = arr; // 相当于 a=1,b=2,c=3
// 变量个数小于数组元素个数无影响
let [a, b] = arr;
// 变量个数大于数组元素个数,多出来的赋值为 undefined
let [a, b, c, d] = arr; // d为undefined
// 解构时也可以使用默认值
let [a, b, c = 33, d = 44] = arr; // c的值还是3,d的值是44
// 只取部分元素可以使用占位
let [, b] = arr; // b为2
let [a, ...b] = arr; // 配合剩余运算, a为1,b为[2,3]
It should be noted that the spread operator (remainder operation) ...
can only appear at the end of the destructuring syntax.
Deconstruction of objects
When objects are deconstructed, the names must be consistent, and there is no requirement for the order.
let obj = {
a: 1, b: 2};
let {
x, y} = obj; // x和y均为 undefined
let {
a, b} = obj; // a为1,b为2
let {
b, a} = obj; // 同上
During object destructuring, variables can also be renamed.
let obj = {
a: 1, b: 2};
let {
a: x, b: y} = obj;
// a , b 会报未定义的错
// x为1,y为2
Use the spread operator to obtain some properties of the object
let obj = {
a: 1, b: 2, c: 3};
let {
a, ...b} = obj;
// a为1
// b为{b: 2, c: 3}
Destructuring using existing variables
let x, y;
({
a: x, b: y} = {
a: 1, b: 2, c: 3});
// x为1
// y为2
It should be noted that because {}
the content in will be regarded as a code block by some browsers , it needs to be wrapped in()
brackets .
Object destructuring uses default values
let x, y, z;
({
a: x, b: y, d: z = {
num: 1}} = {
a: 1, b: 2, c: 3});
// x为1
// y为2
// z为 {num: 1}