12 個(gè)提升 JavaScript 開發(fā)效率的實(shí)用技巧
下面列出了 12 個(gè) JavaScript 小技巧,這些技巧可以幫助你編寫更簡潔、高效的代碼。
如果你已經(jīng)在使用其中的一些技巧,那就鞏固一下吧!需要注意的是為了兼容舊版瀏覽器,記得按需注入墊片(polyfill)。
1. 空值合并運(yùn)算符(??)
使用 ?? 來賦默認(rèn)值,當(dāng) ?? 的左側(cè)值為 null 或者 undefined 時(shí),?? 就會(huì)使用右側(cè)的默認(rèn)值。
const placeholder = props.placeholder ?? '請(qǐng)輸入'
console.log(placeholder) // props.placeholder 為 null 或 undefined 時(shí),輸出“請(qǐng)輸入”
?? 對(duì)比函數(shù)或解構(gòu)默認(rèn)值,唯一的區(qū)別在于對(duì) null 的處理,?? 如上在面對(duì) null 時(shí)也會(huì)使用默認(rèn)值,而函數(shù)或解構(gòu)默認(rèn)值則會(huì)使用 null。
function foo(text = 'default') {
return text
}
let input1
console.log(input1 ?? 'default', foo(input1))
// 輸出 default default
const input2 = null
console.log(input2 ?? 'default', foo(input2))
// 輸出 default null
const input3 = 'value'
console.log(input3 ?? 'default', foo(input3))
// 輸出 value value
在項(xiàng)目代碼中,也會(huì)看到使用邏輯或運(yùn)算符 || 來賦默認(rèn)值,|| 運(yùn)算符在左側(cè)值為 0、空字符串('')、NaN、false、null、undefined 等 falsy 值時(shí),都會(huì)使用默認(rèn)值。
let input1
console.log(input1 ?? 'default', input1 || 'default')
// 輸出 default default
const input2 = false
console.log(input2 ?? 'default', input2 || 'default')
// 輸出 false default
const input3 = 'value'
console.log(input3 ?? 'default', input3 || 'default')
// 輸出 value value
故推薦使用 ?? 來賦默認(rèn)值,也可以使用函數(shù)或解構(gòu)默認(rèn)值,不過要注意 null 值,而 || 更適用于 if 等邏輯判斷。
2. 可選鏈操作符(?.)
可選鏈運(yùn)算符(?.)用于訪問對(duì)象的屬性或方法,當(dāng)訪問的對(duì)象或方法是 undefined 或 null,表達(dá)式會(huì)短路并計(jì)算為 undefined,而不是拋出錯(cuò)誤。
const obj = {
foo: { bar: { a: 3 } }
}
const obj2 = {}
function getA(o) {
return o && o.foo && o.foo.bar && o.foo.bar.a
}
function getA2(o) {
return o?.foo?.bar?.a
}
// 用 && 來獲取深層對(duì)象
console.log(getA(obj)) // 輸出3
console.log(getA(obj2)) // 輸出 undefined
console.log(getA2(obj)) // 輸出3
console.log(getA2(obj2)) // 輸出 undefined
可以看到使用可選鏈運(yùn)算符(?.)在獲取對(duì)象屬性上使用會(huì)更方便。
3. 使用解構(gòu)賦值
解構(gòu)賦值可以快速提取對(duì)象或數(shù)組中的值,減少冗余代碼。
// 對(duì)象解構(gòu)
const user = { name: 'John', age: 30 };
const { name, age } = user;
console.log(name, age); // John 30
// 數(shù)組解構(gòu)
const numbers = [1, 2, 3];
const [first, second] = numbers;
console.log(first, second); // 1 2
4. 字符串方法
使用 startsWith、endsWith、includes 方法來判斷字符串是否包含某個(gè)子串。
'Hello World'.startsWith('Hello') // true
'Hello World'.endsWith('World') // true
'Hello World'.includes('World') // true
相比與 indexOf 方法,startsWith、endsWith、includes 代碼可讀性更高。
const isPython = 'Hello Python'.indexOf('Python') !== -1 // true
const isJS = 'Hello JavaScript'.includes('JavaScript') // true
5. 數(shù)組方法
使用 map、filter、some、every 等方法來操作數(shù)組。
const arr = [
{ name: '小明', age: 16 },
{ name: '張三', age: 18 },
{ name: '李四', age: 20 }
]
const ageArr = arr.map(item => item.age) // [16, 18, 20]
const adults = arr.filter(item => item.age >= 18) // [{ name: '張三', age: 18 }, { name: '李四', age: 20 }]
const hasChild = arr.some(item => item.age < 18) // true
const isAllAdults = arr.every(item => item.age >= 18) // false
相比于使用 for 循環(huán)遍歷數(shù)組來寫業(yè)務(wù)邏輯,map、filter、some、every 等方法讓你編碼更高效,同時(shí)可讀性更高。
6. 使用 Set 去重
Set 可以快速去除數(shù)組中的重復(fù)項(xiàng)。
const numbers = [1, 2, 2, 3, 4, 4];
const uniqueNumbers = [...new Set(numbers)];
console.log(uniqueNumbers); // [1, 2, 3, 4]
7. 使用 Array.from 將類數(shù)組轉(zhuǎn)換為數(shù)組
將 NodeList、arguments 等類數(shù)組對(duì)象轉(zhuǎn)換為真正的數(shù)組。
const nodeList = document.querySelectorAll('div');
const divArray = Array.from(nodeList);
8. 使用策略模式優(yōu)化 if
在一些場景中,if 分支會(huì)比較多,可以使用策略模式優(yōu)化。
// if 判斷
function renderSports = (sports) => {
if (sports === 'basketball') {
return'籃球'
} elseif (sports === 'football') {
return'足球'
} elseif (sports === 'tennis') {
return'網(wǎng)球'
} else {
return'--'
}
}
// 策略模式優(yōu)化
function renderSports2 = (sports) => {
const sportsMap = {
basketball: '籃球',
football: '足球',
tennis: '網(wǎng)球',
}
return sportsMap[sports] || '--'
}
使用策略模式優(yōu)化后,可以少寫一些 if 語句,代碼也更符合設(shè)計(jì)模式。
9. 使用快速生成代碼片段
VSCode 中有提供代碼片段插件,這些插件能幫助你高效的寫代碼,當(dāng)然你也可以自己編寫代碼片段。
10. Chrome DevTools 替換接口內(nèi)容
當(dāng)接口返回的內(nèi)容無法覆蓋頁面所有展示情況時(shí),我們可以使用 Chrome DevTools 的替換內(nèi)容功能來修改接口響應(yīng),從而在不用本地模擬數(shù)據(jù)的情況下完成功能驗(yàn)證。
11. 從控制臺(tái)復(fù)制長變量
Chrome 控制臺(tái)遇到內(nèi)容比較長的變量時(shí),不會(huì)直接平鋪展示全部內(nèi)容,比如字符串較長時(shí)中間會(huì)顯示省略號(hào)、數(shù)組較長時(shí)會(huì)分塊展示等。如果你想復(fù)制這個(gè)內(nèi)容,就會(huì)比較困難,這時(shí)可以使用 Chrome Devtools 的復(fù)制變量功能。
12. 使用 classnames 處理類名
使用 classnames 能更高效的處理類名,同時(shí)還能使類名邏輯更清晰,便于理解和維護(hù)。
// 直接處理類名
let buttonClass = 'btn';
if (isPrimary) {
buttonClass += ' btn-primary';
}
if (isDisabled) {
buttonClass += ' btn-disabled';
}
// 使用 classNames 處理類名
const buttonClass = classNames('btn', {
'btn-primary': isPrimary,
'btn-disabled': isDisabled,
})