JavaScript 操作符/運(yùn)算符
在 JavaScript 中,有一些操作符可以使代碼更簡潔、易讀和高效。以下是一些常見的操作符:
1、可選鏈操作符(optional chaining operator)
?.
是可選鏈操作符(optional chaining operator)。?.
可選鏈操作符用于訪問可能為空或未定義的屬性或方法,它允許我們安全地訪問嵌套對象的屬性,如果中間的屬性為空或未定義,則不會(huì)拋出錯(cuò)誤,而是返回 undefined。例如:
const obj = {
foo: {
bar: 123
}
};
// 普通訪問屬性的方式
const x = obj.foo.bar; // x = 123
// 使用可選鏈操作符
const y = obj?.foo?.bar; // y = 123
// 如果對象未定義,則返回 undefined
const z = undefined?.foo?.bar; // z = undefined
2、空值合并操作符(nullish coalescing operator)
??
是空值合并操作符(nullish coalescing operator)。??
空值合并操作符用于檢查一個(gè)變量是否為 null 或 undefined,如果是,則返回一個(gè)默認(rèn)值,否則返回該變量的值。與傳統(tǒng)的邏輯運(yùn)算符 ||
不同,??
只會(huì)在左側(cè)的值為 null 或 undefined 時(shí)返回右側(cè)的默認(rèn)值,對于其他假值(如空字符串、0、false 等)并不會(huì)返回默認(rèn)值,而是會(huì)返回它本身。例如:
const x = undefined ?? 'default'; // x = 'default'
const y = null ?? 'default'; // y = 'default'
const z = 'value' ?? 'default'; // z = 'value'
const a = '' ?? 'default'; // a = ''
const b = '' || 'default'; // b = 'default'
需要注意的是,??
操作符需要在 ES11 及以上的版本才能使用。
3、箭頭函數(shù)(Arrow Function)
使用箭頭(=>)可以更簡潔地定義函數(shù)。例如:
// const add = (a, b) => {
// return a + b;
// };
// 上述方式簡寫為:
const add = (a, b) => a + b;
console.log(add(1, 2)); // 3
const obj = {
x: 1,
add(y) {
return this.x + y;
},
double: () => this.x * 2,
};
console.log(obj.add(2)); // 3
console.log(obj.double()); // NaN
注意,箭頭函數(shù)中的 this 指向的是定義時(shí)的上下文,而不是調(diào)用時(shí)的上下文。
4、模板字面量(Template Literals)
使用反引號(`)可以定義包含變量、表達(dá)式和換行符的字符串。例如:
const name = "Alice";
const age = 20;
console.log(`My name is ${name}, and I am ${age} years old.`);
// 'My name is Alice, and I am 20 years old.'
5、展開操作符(Spread Operator)
使用三個(gè)點(diǎn)(...)可以將數(shù)組或?qū)ο笳归_為一個(gè)列表或多個(gè)參數(shù)。例如:
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const arr3 = [...arr1, ...arr2];
console.log(arr3); // [1, 2, 3, 4, 5, 6]
const obj1 = { x: 1, y: 2 };
const obj2 = { z: 3 };
const obj3 = { ...obj1, ...obj2 };
console.log(obj3); // { x: 1, y: 2, z: 3 }
6、短路求值(Short-circuit Evaluation)
使用邏輯運(yùn)算符&&
和||
可以進(jìn)行短路求值,簡化條件分支的寫法。例如:
const obj = { prop: "value" };
const propValue = obj.prop || "default";
console.log(propValue); // 'value'
const arr = [];
const firstValue = arr[0] && arr[0].prop;
console.log(firstValue); // undefined
7、簡寫的條件語句(Conditional (Ternary) Operator)
使用問號和冒號(?:)可以簡化 if-else 語句的寫法。例如:
const age = 20;
const message = age >= 18 ? "You are an adult" : "You are not an adult";
console.log(message); // 'You are an adult'
使用邏輯運(yùn)行符&&
和||
簡化 if-else 語句的寫法。例如:
const err = undefined;
if (err) {
console.error(err);
}
// 上述語句可簡寫為:
err && console.error(err);
8、簡寫的自增和自減操作符(Short-circuit Evaluation)
使用雙加號(++)和雙減號(--)可以簡化變量的自增和自減操作。例如:
let count = 0;
count++;
console.log(count); // 1
let num = 5;
const result = --num;
console.log(result); // 4
9、簡寫的賦值操作符(Assignment Operator)
使用加等號(+=)、減等號(-=)、乘等號(*=)、除等號(/=)等可以簡化復(fù)合賦值操作。例如:
let count = 0;
count += 1;
console.log(count); // 1
let num = 5;
num *= 2;
console.log(num); // 10
10、雙重否定運(yùn)算符(Double NOT Operator)
雙重否定運(yùn)算符(Double NOT Operator)即為兩個(gè)連續(xù)的嘆號("!!"),也稱為邏輯非非運(yùn)算符。它可以將一個(gè)值轉(zhuǎn)換為其對應(yīng)的布爾值。例如:
const x = "hello";
console.log(!!x); // true
const y = 0;
console.log(!!y); // false
需要注意的是,使用!!
運(yùn)算符進(jìn)行布爾值轉(zhuǎn)換時(shí),要注意避免隱式類型轉(zhuǎn)換帶來的副作用,以免導(dǎo)致意外的行為。
11、?: 在 TypeScript 中表示可選屬性
在 TypeScript 中,可以使用 ?
表示一個(gè)屬性是可選的。例如:文章來源:http://www.zghlxwxcb.cn/news/detail-418275.html
interface Person {
name: string;
age?: number;
}
const person1: Person = { name: "Alice" };
const person2: Person = { name: "Bob", age: 20 };
在上面的例子中,Person 接口有一個(gè)可選屬性 age,這意味著可以創(chuàng)建一個(gè) Person 類型的對象,其中 age 屬性是可選的。文章來源地址http://www.zghlxwxcb.cn/news/detail-418275.html
到了這里,關(guān)于JavaScript 操作符的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!