16 個(gè)有用的 TypeScript 和 JavaScript 技巧

英文 | https://blog.logrocket.com/16-useful-typescript-javascript-shorthands-know/
翻譯 | 楊小愛
[condition] ? [true result] : [false result]以下示例演示了傳統(tǒng)的 if...else 語(yǔ)句及其使用三元運(yùn)算符的等效簡(jiǎn)寫:
// Longhandconst mark = 80if (mark >= 65) {return "Pass"} else {return "Fail"}// Shorthandconst mark = 80return mark >= 65 ? "Pass" : "Fail"
02、短路評(píng)估
替換 if...else 語(yǔ)句的另一種方法是使用短路評(píng)估。此技巧使用邏輯 OR 運(yùn)算符 || 當(dāng)預(yù)期值是虛假的時(shí),為變量分配默認(rèn)值。
以下示例演示了如何使用短路評(píng)估:
// Longhandlet str = ''let finalStrif (str !== null && str !== undefined && str != '') {finalStr = str} else {finalStr = 'default string'}// Shorthandlet str = ''let finalStr = str || 'default string' // 'default string
03、空值合并運(yùn)算符
無(wú)效的合并運(yùn)算符 ?? 類似于短路評(píng)估,因?yàn)樗糜跒樽兞糠峙淠J(rèn)值。但是,空值合并運(yùn)算符僅在預(yù)期值也為空值時(shí)使用默認(rèn)值。
換句話說(shuō),如果預(yù)期值是虛假的但不是空值,它將不會(huì)使用默認(rèn)值。
以下是空值合并運(yùn)算符的兩個(gè)示例:
// Example 1// Longhandlet str = ''let finalStrif (str !== null && str !== undefined) {finalStr = 'default string'} else {finalStr = str}// Shorthandlet str = ''let finaStr = str ?? 'default string' // ''// Example 2// Longhandlet num = nulllet actualNumif (num !== null && num !== undefined) {actualNum = num} else {actualNum = 0}// Shorthandlet num = nulllet actualNum = num ?? 0 // 0
04、模板文字
借助 JavaScript 強(qiáng)大的 ES6 特性,我們可以使用模板文字而不是使用 + 來(lái)連接字符串中的多個(gè)變量。要使用模板文字,請(qǐng)將字符串包裝在 `` 中,并將變量包裝在這些字符串中的 ${} 中。
下面的示例演示了如何使用模板文字來(lái)執(zhí)行字符串插值:
const name = 'Iby'const hobby = 'to read'// Longhandconst fullStr = name + ' loves ' + hobby // 'Iby loves to read'// Shorthandconst fullStr = `${name} loves ${hobby}`
我們還可以使用模板文字來(lái)構(gòu)建多行字符串,而無(wú)需使用 \n。例如:
// Shorthandconst name = 'Iby'const hobby = 'to read'const fullStr = `${name} loves ${hobby}.She also loves to write!`
05、對(duì)象屬性賦值簡(jiǎn)寫
在 JavaScript 和 TypeScript 中,我們可以通過(guò)在對(duì)象字面量中提及變量來(lái)以簡(jiǎn)寫形式將屬性分配給對(duì)象。為此,必須使用預(yù)期的鍵命名變量。
請(qǐng)參閱下面的對(duì)象屬性分配簡(jiǎn)寫示例:
Longhandconst obj = {x: 1,y: 2,z: 3}Shorthandconst x = 8const y = 10const obj = { x, y }
06、可選鏈接
點(diǎn)表示法允許我們?cè)L問(wèn)對(duì)象的鍵或值。使用可選鏈接,我們可以更進(jìn)一步,即使我們不確定它們是否存在或已設(shè)置,也可以讀取鍵或值。當(dāng)鍵不存在時(shí),來(lái)自可選鏈接的值是未定義的。
請(qǐng)參閱下面的可選鏈接示例:
const obj = {x: {y: 1,z: 2},others: ['test','tested']}// Longhandif (obj.hasProperty('others') && others.length >= 2) {console.log('2nd value in others: ', obj.others[1])}// Shorthandconsole.log('2nd value in others: ', obj.others?.[1]) // 'tested'console.log('3rd value in others: ', obj.others?.[2]) // undefined
07、對(duì)象解構(gòu)
除了傳統(tǒng)的點(diǎn)符號(hào)之外,另一種讀取對(duì)象值的方法是將對(duì)象的值解構(gòu)為它們自己的變量。
下面的示例演示了如何使用傳統(tǒng)的點(diǎn)表示法讀取對(duì)象的值,與使用對(duì)象解構(gòu)的速記方法進(jìn)行比較。
const obj = {x: {y: 1,z: 2},other: 'test string'}// Longhandconsole.log('Value of z in x: ', obj.x.z)console.log('Value of other: ', obj.other)// Shorthandconst {x, other} = objconst {z} = xconsole.log('Value of z in x: ', z)console.log('Value of other: ', other)
我們還可以重命名從對(duì)象中解構(gòu)的變量。這是一個(gè)例子:
const obj = {x: 1, y: 2}const {x: myVar} = objectconsole.log('My renamed variable: ', myVar) // My renamed variable: 1
08、擴(kuò)展運(yùn)算符
擴(kuò)展運(yùn)算符 ... 用于訪問(wèn)數(shù)組和對(duì)象的內(nèi)容。我們可以使用擴(kuò)展運(yùn)算符來(lái)替換數(shù)組函數(shù)(如 concat)和對(duì)象函數(shù)(如 object.assign)。
查看下面的示例,了解如何使用擴(kuò)展運(yùn)算符替換普通數(shù)組和對(duì)象函數(shù)。
// Longhandconst arr = [1, 2, 3]const biggerArr = [4,5,6].concat(arr)const smallObj = {x: 1}const otherObj = object.assign(smallObj, {y: 2})// Shorthandconst arr = [1, 2, 3]const biggerArr = [...arr, 4, 5, 6]const smallObj = {x: 1}const otherObj = {...smallObj, y: 2}
09、對(duì)象循環(huán)
傳統(tǒng)的 JavaScript for 循環(huán)語(yǔ)法如下:
for (let i = 0; i < x; i++) { … }我們可以使用這種循環(huán)語(yǔ)法通過(guò)引用迭代器的數(shù)組長(zhǎng)度來(lái)迭代數(shù)組。
共有三種 for 循環(huán)簡(jiǎn)寫,它們提供了不同的方式來(lái)遍歷數(shù)組對(duì)象:
for...of 訪問(wèn)數(shù)組條目
for...in 用于訪問(wèn)數(shù)組的索引和在對(duì)象字面量上使用時(shí)的鍵
Array.forEach 使用回調(diào)函數(shù)對(duì)數(shù)組元素及其索引執(zhí)行操作
請(qǐng)注意 Array.forEach 回調(diào)有三個(gè)可能的參數(shù),按以下順序調(diào)用:
正在進(jìn)行的迭代的數(shù)組元素
元素的索引
數(shù)組的完整副本
下面的示例演示了這些對(duì)象循環(huán)簡(jiǎn)寫的作用:
// Longhandconst arr = ['Yes', 'No', 'Maybe']for (let i = 0; i < arr.length; i++) {console.log('Here is item: ', arr[i])}// Shorthandfor (let str of arr) {console.log('Here is item: ', str)}arr.forEach((str) => {console.log('Here is item: ', str)})for (let index in arr) {console.log(`Item at index ${index} is ${arr[index]}`)}// For object literalsconst obj = {a: 1, b: 2, c: 3}for (let key in obj) {console.log(`Value at key ${key} is ${obj[key]}`)}
10、Array.indexOf 使用按位運(yùn)算符的簡(jiǎn)寫
我們可以使用 Array.indexOf 方法查找數(shù)組中是否存在項(xiàng)目。如果該項(xiàng)目存在于數(shù)組中,則此方法返回該項(xiàng)目的索引位置,如果不存在則返回 -1。
在 JavaScript 中,0 是一個(gè)假值,而小于或大于 0 的數(shù)字被認(rèn)為是真值。通常,這意味著我們需要使用 if...else 語(yǔ)句來(lái)使用返回的索引來(lái)確定項(xiàng)目是否存在。
使用按位運(yùn)算符 ~ 而不是 if...else 語(yǔ)句可以讓我們獲得大于或等于 0 的任何值的真值。
下面的示例演示了使用按位運(yùn)算符而不是 if...else 語(yǔ)句的 Array.indexOf 速記:
const arr = [10, 12, 14, 16]const realNum = 10const fakeNum = 20const realNumIndex = arr.indexOf(realNum)const noneNumIndex = arr.indexOf(fakeNum)// Longhandif (realNumIndex > -1) {console.log(realNum, ' exists!')} else if (realNumIndex === -1) {console.log(realNum, ' does not exist!')}if (noneNumIndex > -1) {console.log(fakeNum, ' exists!')} else if (noneNumIndex === -1) {console.log(fakeNum, ' does not exist!')}// Shorthandconsole.log(realNum + (~realNumIndex ? ' exists!' : ' does not exist!')console.log(fakeNum + (~noneNumIndex ? ' exists!' : ' does not exist!')
11、使用 !! 將值轉(zhuǎn)換為布爾值
在 JavaScript 中,我們可以使用 !![variable] 簡(jiǎn)寫將任何類型的變量轉(zhuǎn)換為布爾值。
查看使用 !! 的示例 [變量] 將值轉(zhuǎn)換為布爾值的簡(jiǎn)寫:
// Longhandconst simpleInt = 3const intAsBool = Boolean(simpleInt)// Shorthandconst simpleInt = 3const intAsBool = !!simpleInt
12、箭頭/lambda 函數(shù)表達(dá)式
JavaScript 中的函數(shù)可以使用箭頭函數(shù)語(yǔ)法來(lái)編寫,而不是顯式使用 function 關(guān)鍵字的傳統(tǒng)表達(dá)式。箭頭函數(shù)類似于其他語(yǔ)言中的 lambda 函數(shù)。
看看這個(gè)使用箭頭函數(shù)表達(dá)式以簡(jiǎn)寫形式編寫函數(shù)的示例:
// Longhandfunction printStr(str) {console.log('This is a string: ', str)}printStr('Girl!')// Shorthandconst printStr = (str) => {console.log('This is a string: ', str)}printStr('Girl!')// Shorthand TypeScript (specifying variable type)const printStr = (str: string) => {console.log('This is a string: ', str)}printStr('Girl!')
13、使用箭頭函數(shù)表達(dá)式的隱式返回
在 JavaScript 中,我們通常使用 return 關(guān)鍵字從函數(shù)中返回一個(gè)值。當(dāng)我們使用箭頭函數(shù)語(yǔ)法定義函數(shù)時(shí),我們可以通過(guò)排除大括號(hào) {} 來(lái)隱式返回一個(gè)值。
對(duì)于多行語(yǔ)句,例如表達(dá)式,我們可以將返回表達(dá)式包裹在括號(hào) () 中。
下面的示例演示了使用箭頭函數(shù)表達(dá)式從函數(shù)中隱式返回值的簡(jiǎn)寫代碼:
// Longhandfunction capitalize(name) {return name.toUpperCase()}function add(numA, numB) {return numA + numB}// Shorthandconst capitalize = (name) => name.toUpperCase()const add = (numA, numB) => (numA + numB)// Shorthand TypeScript (specifying variable type)const capitalize = (name: string) => name.toUpperCase()const add = (numA: number, numB: number) => (numA + numB)
14、雙位非運(yùn)算符
在 JavaScript 中,我們通常使用內(nèi)置的 Math 對(duì)象來(lái)訪問(wèn)數(shù)學(xué)函數(shù)和常量。但是,一些函數(shù)允許我們?cè)诓灰?Math 對(duì)象的情況下訪問(wèn)函數(shù)。
例如,應(yīng)用按位 NOT 運(yùn)算符兩次 ~~ 允許我們獲得一個(gè)值的 Math.floor()。
查看下面的示例,了解如何將雙位 NOT 運(yùn)算符用作 Math.floor() 速記:
// Longhandconst num = 4.5const floorNum = Math.floor(num) // 4// Shorthandconst num = 4.5const floorNum = ~~num // 4
15、指數(shù)冪速記
另一個(gè)具有用的技巧是 Math.pow() 函數(shù)。使用內(nèi)置 Math 對(duì)象的替代方法是 ** 使用技巧。
下面的示例演示了這種指數(shù)冪的簡(jiǎn)寫:
// Longhandconst num = Math.pow(3, 4) // 81// Shorthandconst num = 3 ** 4 // 81
16、TypeScript 構(gòu)造函數(shù)簡(jiǎn)寫
通過(guò) TypeScript 中的構(gòu)造函數(shù)創(chuàng)建一個(gè)類并為類屬性賦值有一個(gè)簡(jiǎn)寫。使用此方法時(shí),TypeScript 會(huì)自動(dòng)創(chuàng)建和設(shè)置類屬性。
這個(gè)速記是 TypeScript 獨(dú)有的,在 JavaScript 類定義中不可用。
看看下面的例子,看看 TypeScript 構(gòu)造函數(shù)的簡(jiǎn)寫:
// Longhandclass Person {private name: stringpublic age: intprotected hobbies: string[]constructor(name: string, age: int, hobbies: string[]) {this.name = namethis.age = agethis.hobbies = hobbies}}// Shorthandclass Person {constructor(private name: string,public age: int,protected hobbies: string[]) {}}
總結(jié)
以上這些只是一些最常用的 JavaScript 和 TypeScript 技巧。請(qǐng)記住,使用這些代碼并不總是最好的選擇。最重要的是編寫其他開發(fā)人員可以輕松閱讀的簡(jiǎn)潔易懂的代碼。
如過(guò)你還有最喜歡的 JavaScript 或 TypeScript 技巧的話,請(qǐng)?jiān)谠u(píng)論中與我們分享!
最后,感謝你的閱讀,祝編程愉快,如果你覺得有用的話,請(qǐng)記得分享給你身邊做開發(fā)的朋友,也許能夠幫助到他。
學(xué)習(xí)更多技能
請(qǐng)點(diǎn)擊下方公眾號(hào)
![]()

