1. 有條件地添加對(duì)象添加屬性?
const condition = true;
const person = {
? ? id: 1,
? ? name: 'John Doe',
? ? ...(condition && { age: 16 })
}
要點(diǎn):&&都為true返回第最后一個(gè)求值表達(dá)式,...擴(kuò)展成person對(duì)象的一部分。
2. 檢查屬性是否存在對(duì)象中
用in檢查js對(duì)象中是否存在某個(gè)值
const person = { name: 'a', sa: 1111 }
console.log( name in person ) // true
3. 空值合并??操作符
可以用??來(lái)檢查變量是否為null或undefined,當(dāng)變量是其中一個(gè),則返回右側(cè)操作數(shù),不是返回變量
const foo = null ?? 'hello'? ? ? // hello
4. 可選鏈?.
我們是不是經(jīng)常遇到這樣的錯(cuò)誤:?TypeError: Cannot read property ‘foo’ of null。這對(duì)每一個(gè)毅開(kāi)發(fā)人員來(lái)說(shuō)都是一個(gè)煩人的問(wèn)題。引入可選鏈就是為了解決這個(gè)問(wèn)題。一起來(lái)看看:
console.log(book.author && book.author.age) => console.log(book.author?.age)
console.log(person.printName()) => console.log(person.aaa?.()) //函數(shù)形式
5. 使用??!操作符
!!運(yùn)算符可用于將表達(dá)式的結(jié)果快速轉(zhuǎn)換成布爾值
const a = '111'
console.log(!!a) // true
6.?字符串和整數(shù)轉(zhuǎn)換
使用+操作符將字符串快速轉(zhuǎn)換為數(shù)字:
const stringNumer = '123';console.log(+stringNumer); //123console.log(typeof +stringNumer); //'number'復(fù)制代碼
要將數(shù)字快速轉(zhuǎn)換為字符串,也可以使用+操作符,后面跟著一個(gè)空字符串:
const myString = 25 + '';console.log(myString); //'25'console.log(typeof myString); //'string'復(fù)制代碼
這些類(lèi)型轉(zhuǎn)換非常方便,但它們的清晰度和代碼可讀性較差。所以實(shí)際開(kāi)發(fā),需要慎重的選擇使用。
7. replaceAll 方法
在 JS 中,要將所有出現(xiàn)的字符串替換為另一個(gè)字符串,我們需要使用如下所示的正則表達(dá)式:
const str = 'Red-Green-Blue';// 只規(guī)制第一次出現(xiàn)的str.replace('-', ' '); // Red Green-Blue// 使用 RegEx 替換所有匹配項(xiàng)str.replace(/\-/g, ' '); // Red Green Blue復(fù)制代碼
但是在 ES12 中,一個(gè)名為replaceAll的新方法被添加到String.prototype中,它用另一個(gè)字符串值替換所有出現(xiàn)的字符串。
str.replaceAll('-', ' '); // Red Green Blue