七個(gè)很有用的 JavaScript 技巧
1.用“fill”初始化數(shù)組
初始化一個(gè)固定長(zhǎng)度的數(shù)組,每一項(xiàng)都是“fatfish”。
// ?
let array = []
const len = 100
for(let i = 0; i < len; i++){
array[i] = 'fatfish'
}
其實(shí),使用 fill 就很簡(jiǎn)單了。
// ?
let array = Array(100).fill('fatfish')
2. 使用對(duì)象代替“switch”
我們經(jīng)常使用 switch 來(lái)處理不同的事情,但是你有沒(méi)有想過(guò)使用對(duì)象來(lái)大大簡(jiǎn)化你的代碼?(它適用于一些簡(jiǎn)單的場(chǎng)景)
// ?
const n = 1
let result
switch (n) {
case 1:
result = 'res-1'
break
case 2:
result = 'res-2'
break
case 3:
result = 'res-3'
break
// ...There are a lot more
}
你只需要使用一個(gè)對(duì)象來(lái)實(shí)現(xiàn)你的目標(biāo)。
// ?
const n = 1
const nMap = {
1: 'res-1',
2: 'res-2',
3: 'res-3'
}
const result = nMap[ n ]
3. 使用“? ……:……”而不是“if… else…”
很多時(shí)候簡(jiǎn)單的條件判斷并不需要使用“if”。
// ?
const n = 18
let result
if (n % 2 === 0) {
result = 'even number'
} else {
result = 'odd number'
}
只需使用三元表達(dá)式即可簡(jiǎn)化代碼。
// ?
const n = 18
let result = n % 2 === 0 ? 'even number' : 'odd number'
4.使用“includes”方法而不是多個(gè)“if”
你經(jīng)常寫(xiě)這樣的代碼嗎?多個(gè)條件可以觸發(fā)一個(gè)邏輯。隨著你的業(yè)務(wù)增長(zhǎng),你可能需要寫(xiě)更多的“||”,這很糟糕。
// ?
const n = 1
if (n === 1 || n === 2 || n === 3 || n === 4 || n === 5) {
// ...
}
使用包含使您的代碼更加易于維護(hù)。
// ?
const n = 1
const conditions = [ 1, 2, 3, 4, 5 ] // You just need to add new numbers here
if (conditions.includes(n)) {
// ...
}
5.使用ES6函數(shù)的默認(rèn)參數(shù)
為什么不使用默認(rèn)參數(shù)呢?
// ?
const func = (name) => {
name = name || 'fatfish'
console.log(name)
}
// ?
const func = (name = 'fatfish') => {
console.log(name)
}
6. 使用“+”將字符串轉(zhuǎn)換為數(shù)字
您可能正在使用 Number() 和 parseInt() 將字符串轉(zhuǎn)換為數(shù)字。
// ?
let str = '123'
let num = Number(str) // 123
let num2 = parseInt(str) // 123
實(shí)際上使用“+”更容易。
// ?
let str = '123'
let num = +str // 123
7. 使用“JSON.stringify”輸出更漂亮的信息
這是一個(gè)深度嵌套的對(duì)象,您可以使用 console.log 來(lái)打印它。
// ?
const bigObj = {
name: 'fatfish',
obj: {
name: 'fatfish',
obj: {
name: 'fatfish',
obj: {
name: 'fatfish',
obj: {
name: 'fatfish',
// ...
}
}
}
}
}
console.log(bigObj)
但這樣不方便查看具體屬性,我們需要手動(dòng)展開(kāi)各個(gè)級(jí)別才能看到數(shù)據(jù)。
// ?
const bigObj = {
name: 'fatfish',
obj: {
name: 'fatfish',
obj: {
name: 'fatfish',
obj: {
name: 'fatfish',
obj: {
name: 'fatfish',
// ...
}
}
}
}
}
console.log(JSON.stringify(bigObj, null, 2))
這真的非常方便和直觀。