新聞中心
JavaScript 和 TypeScript 共享許多有用的常用代碼概念的技巧替代方案。這些代碼替代方案可以幫助減少代碼行數(shù),這也是我們努力的目標(biāo)。

在本文中,我們將分享 16 個(gè)常見的 TypeScript 和 JavaScript 技巧。我們還將探討如何使用這些速記的示例。
在編寫干凈且可擴(kuò)展的代碼時(shí),使用這些技巧并不總是正確的決定。簡(jiǎn)潔的代碼有時(shí)會(huì)更容易閱讀和更新。我們的代碼必須清晰易讀,并向其他開發(fā)人員傳達(dá)含義和上下文,這一點(diǎn)也很重要。
JavaScript 中可用的所有技巧都可以在 TypeScript 中以相同的語(yǔ)法使用。唯一的細(xì)微差別是在 TypeScript 中指定類型。但是,TypeScript 構(gòu)造函數(shù)簡(jiǎn)寫是 TypeScript 獨(dú)有的。
現(xiàn)在,我們就正式開始吧。
1、三元運(yùn)算符
三元運(yùn)算符是 JavaScript 和 TypeScript 中最流行的簡(jiǎn)寫之一。它取代了傳統(tǒng)的 if…else 語(yǔ)句。它的語(yǔ)法如下:
[condition] ? [true result] : [false result]
以下示例演示了傳統(tǒng)的 if...else 語(yǔ)句及其使用三元運(yùn)算符的等效簡(jiǎn)寫:
// Longhand
const mark = 80
if (mark >= 65) {
return "Pass"
} else {
return "Fail"
}
// Shorthand
const mark = 80
return mark >= 65 ? "Pass" : "Fail"
2、短路評(píng)估
替換 if...else 語(yǔ)句的另一種方法是使用短路評(píng)估。此技巧使用邏輯 OR 運(yùn)算符 || 當(dāng)預(yù)期值是虛假的時(shí),為變量分配默認(rèn)值。
以下示例演示了如何使用短路評(píng)估:
// Longhand
let str = ''
let finalStr
if (str !== null && str !== undefined && str != '') {
finalStr = str
} else {
finalStr = 'default string'
}
// Shorthand
let str = ''
let finalStr = str || 'default string' // 'default string
3、空值合并運(yùn)算符
無(wú)效的合并運(yùn)算符 ?? 類似于短路評(píng)估,因?yàn)樗糜跒樽兞糠峙淠J(rèn)值。但是,空值合并運(yùn)算符僅在預(yù)期值也為空值時(shí)使用默認(rèn)值。
換句話說,如果預(yù)期值是虛假的但不是空值,它將不會(huì)使用默認(rèn)值。
以下是空值合并運(yùn)算符的兩個(gè)示例:
// Example 1
// Longhand
let str = ''
let finalStr
if (str !== null && str !== undefined) {
finalStr = 'default string'
} else {
finalStr = str
}
// Shorthand
let str = ''
let finaStr = str ?? 'default string' // ''
// Example 2
// Longhand
let num = null
let actualNum
if (num !== null && num !== undefined) {
actualNum = num
} else {
actualNum = 0
}
// Shorthand
let num = null
let actualNum = num ?? 0 // 0
4、模板文字
借助 JavaScript 強(qiáng)大的 ES6 特性,我們可以使用模板文字而不是使用 + 來連接字符串中的多個(gè)變量。要使用模板文字,請(qǐng)將字符串包裝在 `` 中,并將變量包裝在這些字符串中的 ${} 中。
下面的示例演示了如何使用模板文字來執(zhí)行字符串插值:
const name = 'Iby'
const hobby = 'to read'
// Longhand
const fullStr = name + ' loves ' + hobby // 'Iby loves to read'
// Shorthand
const fullStr = `${name} loves ${hobby}`
我們還可以使用模板文字來構(gòu)建多行字符串,而無(wú)需使用 \n。例如:
// Shorthand
const name = 'Iby'
const hobby = 'to read'
const fullStr = `${name} loves ${hobby}.
She also loves to write!`
5、對(duì)象屬性賦值簡(jiǎn)寫
在 JavaScript 和 TypeScript 中,我們可以通過在對(duì)象字面量中提及變量來以簡(jiǎn)寫形式將屬性分配給對(duì)象。為此,必須使用預(yù)期的鍵命名變量。
請(qǐng)參閱下面的對(duì)象屬性分配簡(jiǎn)寫示例:
// Longhand
const obj = {
x: 1,
y: 2,
z: 3
}
// Shorthand
const x = 8
const y = 10
const obj = { x, y }
6、可選鏈接
點(diǎn)表示法允許我們?cè)L問對(duì)象的鍵或值。使用可選鏈接,我們可以更進(jìn)一步,即使我們不確定它們是否存在或已設(shè)置,也可以讀取鍵或值。當(dāng)鍵不存在時(shí),來自可選鏈接的值是未定義的。
請(qǐng)參閱下面的可選鏈接示例:
const obj = {
x: {
y: 1,
z: 2
},
others: [
'test',
'tested'
]
}
// Longhand
if (obj.hasProperty('others') && others.length >= 2) {
console.log('2nd value in others: ', obj.others[1])
}
// Shorthand
console.log('2nd value in others: ', obj.others?.[1]) // 'tested'
console.log('3rd value in others: ', obj.others?.[2]) // undefined
7、對(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'
}
// Longhand
console.log('Value of z in x: ', obj.x.z)
console.log('Value of other: ', obj.other)
// Shorthand
const {x, other} = obj
const {z} = x
console.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} = object
console.log('My renamed variable: ', myVar) // My renamed variable: 1
8、擴(kuò)展運(yùn)算符
擴(kuò)展運(yùn)算符 ... 用于訪問數(shù)組和對(duì)象的內(nèi)容。我們可以使用擴(kuò)展運(yùn)算符來替換數(shù)組函數(shù)(如 concat)和對(duì)象函數(shù)(如 object.assign)。
查看下面的示例,了解如何使用擴(kuò)展運(yùn)算符替換普通數(shù)組和對(duì)象函數(shù)。
// Longhand
const arr = [1, 2, 3]
const biggerArr = [4,5,6].concat(arr)
const smallObj = {x: 1}
const otherObj = object.assign(smallObj, {y: 2})
// Shorthand
const arr = [1, 2, 3]
const biggerArr = [...arr, 4, 5, 6]
const smallObj = {x: 1}
const otherObj = {...smallObj, y: 2}
9、對(duì)象循環(huán)
傳統(tǒng)的 JavaScript for 循環(huán)語(yǔ)法如下:
for (let i = 0; i < x; i++) { … }我們可以使用這種循環(huán)語(yǔ)法通過引用迭代器的數(shù)組長(zhǎng)度來迭代數(shù)組。
共有三種 for 循環(huán)簡(jiǎn)寫,它們提供了不同的方式來遍歷數(shù)組對(duì)象:
- for...of 訪問數(shù)組條目
- for...in 用于訪問數(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)寫的作用:
// Longhand
const arr = ['Yes', 'No', 'Maybe']
for (let i = 0; i < arr.length; i++) {
console.log('Here is item: ', arr[i])
}
// Shorthand
for (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 literals
const 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ǔ)句來使用返回的索引來確定項(xiàng)目是否存在。
使用按位運(yùn)算符 ~ 而不是 if...else 語(yǔ)句可以讓我們獲得大于或等于 0 的任何值的真值。
下面的示例演示了使用按位運(yùn)算符而不是 if...else 語(yǔ)句的 Array.indexOf 速記:
const arr = [10, 12, 14, 16]
const realNum = 10
const fakeNum = 20
const realNumIndex = arr.indexOf(realNum)
const noneNumIndex = arr.indexOf(fakeNum)
// Longhand
if (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!')
}
// Shorthand
console.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)寫:
// Longhand
const simpleInt = 3
const intAsBool = Boolean(simpleInt)
// Shorthand
const simpleInt = 3
const intAsBool = !!simpleInt
12、箭頭/lambda 函數(shù)表達(dá)式
JavaScript 中的函數(shù)可以使用箭頭函數(shù)語(yǔ)法來編寫,而不是顯式使用 function 關(guān)鍵字的傳統(tǒng)表達(dá)式。箭頭函數(shù)類似于其他語(yǔ)言中的 lambda 函數(shù)。
看看這個(gè)使用箭頭函數(shù)表達(dá)式以簡(jiǎn)寫形式編寫函數(shù)的示例:
// Longhand
function printStr(str) {
console.log('This is a string: ', str)
}
printStr('Girl!')
// Shorthand
const 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í),我們可以通過排除大括號(hào) {} 來隱式返回一個(gè)值。
對(duì)于多行語(yǔ)句,例如表達(dá)式,我們可以將返回表達(dá)式包裹在括號(hào) () 中。
下面的示例演示了使用箭頭函數(shù)表達(dá)式從函數(shù)中隱式返回值的簡(jiǎn)寫代碼:
// Longhand
function capitalize(name) {
return name.toUpperCase()
}
function add(numA, numB) {
return numA + numB
}
// Shorthand
const 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ì)象來訪問數(shù)學(xué)函數(shù)和常量。但是,一些函數(shù)允許我們?cè)诓灰?Math 對(duì)象的情況下訪問函數(shù)。
例如,應(yīng)用按位 NOT 運(yùn)算符兩次 ~~ 允許我們獲得一個(gè)值的 Math.floor()。
查看下面的示例,了解如何將雙位 NOT 運(yùn)算符用作 Math.floor() 速記:
// Longhand
const num = 4.5
const floorNum = Math.floor(num) // 4
// Shorthand
const num = 4.5
const floorNum = ~~num // 4
15、指數(shù)冪速記
另一個(gè)具有用的技巧是 Math.pow() 函數(shù)。使用內(nèi)置 Math 對(duì)象的替代方法是 ** 使用技巧。
下面的示例演示了這種指數(shù)冪的簡(jiǎn)寫:
// Longhand
const num = Math.pow(3, 4) // 81
// Shorthand
const num = 3 ** 4 // 81
16、TypeScript 構(gòu)造函數(shù)簡(jiǎn)寫
通過 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)寫:
// Longhand
class Person {
private name: string
public age: int
protected hobbies: string[]
constructor(name: string, age: int, hobbies: string[]) {
this.name = name
this.age = age
this.hobbies = hobbies
}
}
// Shorthand
class Person {
constructor(
private name: string,
public age: int,
protected hobbies: string[]
) {}
}
總結(jié)
以上這些只是一些最常用的 JavaScript 和 TypeScript 技巧。請(qǐng)記住,使用這些代碼并不總是最好的選擇。最重要的是編寫其他開發(fā)人員可以輕松閱讀的簡(jiǎn)潔易懂的代碼。
最后,感謝你的閱讀,祝編程愉快,如果你覺得有用的話,請(qǐng)記得分享給你身邊做開發(fā)的朋友,也許能夠幫助到他。
分享名稱:16個(gè)有用的TypeScript和JavaScript技巧
文章URL:http://www.dlmjj.cn/article/djphdhh.html


咨詢
建站咨詢
