使用這11個代碼,可以大大地簡化我們的代碼
在這篇文章中,我將與你分享一些關(guān)于JS的技巧,可以提高你的JS技能。
1.避免if過長
如果判斷值滿足多個條件,我們可能會這么寫:
- if (value === 'a' || value === 'b' || value === 'c') { ... }
像這樣如果有多個條件,if 條件就會很我,可讀性降低,我們可以這樣簡化:
- if (['a', 'b', 'c'].includes(value)) { ... }
2.雙!操作符將任何變量轉(zhuǎn)換為布爾值
!(NOT)運(yùn)算符可以使用兩次!!,這樣可以將任何變量轉(zhuǎn)換為布爾值(像布爾函數(shù)),當(dāng)你需要在處理它之前檢查某個值時非常方便。
- const toto = null
- !!toto // false
- Boolean(toto) // false
- if (!!toto) { } // toto is not null or undefined
3.可選項(xiàng) (?)
在 JS 中,我們需要經(jīng)常檢查對象的某些屬性是否存在,然后才能再處理它,不然會報錯。早期我們可能會這么干:
- const toto = { a: { b: { c: 5 } } }
- if (!!toto.a && !!toto.a.b && !!toto.a.b.c) { ... } // toto.a.b.c exist
如果對象嵌套很深,我們這寫法就難以閱讀,這時可以使用?來簡化:
- if (!!toto.a?.b?.c) { ... } // toto.a.b.c exist
- // 如果鍵不存在,返回 `undefined`。
- const test = toto.a?.b?.c?.d // undefined
4. 如果if中返回值時, 就不要在寫else
經(jīng)常會看到這種寫法:
- if (...) {
- return 'toto'
- } else {
- return 'tutu'
- }
如果if有返回值了,可以這樣寫:
- if (...) {
- return 'toto'
- }
- return 'tutu'
5.避免forEach,多使用filter、map、reduce、every、some
作為初學(xué)者,我們使用了很多forEach函數(shù),但 JS 為我們提供了很多選擇,而且這些函數(shù)是FP(函數(shù)式編程)。
filter
filter() 方法創(chuàng)建一個新數(shù)組, 其包含通過所提供函數(shù)實(shí)現(xiàn)的測試的所有元素。
- const toto = [1, 2, 3, 4]
- // 過濾奇數(shù)
- const evenValue = toto.filter(currentValue => {
- return currentValue % 2 == 0
- }) // [2, 4]
map
map() 方法創(chuàng)建一個新數(shù)組,其結(jié)果是該數(shù)組中的每個元素是調(diào)用一次提供的函數(shù)后的返回值。
- const toto = [1, 2, 3, 4]
- const valueMultiplied = toto.map(currentValue => {
- return currentValue * 2
- }) // [2, 4, 6, 8]
reduce
reduce() 方法對數(shù)組中的每個元素執(zhí)行一個由您提供的reducer函數(shù)(升序執(zhí)行),將其結(jié)果匯總為單個返回值。
- const toto = [1, 2, 3, 4]
- const sum = toto.reduce((accumulator, currentValue) => {
- return accumulator += currentValue
- }, 0) // 10
Some & Every
some() 方法測試數(shù)組中是不是至少有1個元素通過了被提供的函數(shù)測試。它返回的是一個Boolean類型的值。
every() 方法測試一個數(shù)組內(nèi)的所有元素是否都能通過某個指定函數(shù)的測試。它返回一個布爾值。
什么時候使用?
所有項(xiàng)目都符合一個條件可以用 every
- const toto = [ 2, 4 ]
- toto.every(val => val % 2 === 0) // true
- const falsyToto = [ 2, 4, 5 ]
- falsyToto.every(val => val % 2 === 0) // false
只要一個符合條件就行,用some
- const toto = [ 2, 4, 5 ]
- toto.some(val => val % 2 !== 0) // return true
6.不要使用delete來刪除屬性
從一個對象中 delete 一個屬性是非常不好的(性能不好),此外,它還會產(chǎn)生很多副作用。
但是如果你需要刪除一個屬性,你應(yīng)該怎么做?
可以使用函數(shù)方式創(chuàng)建一個沒有此屬性的新對象,如下所示:
- const removeProperty = (target, propertyToRemove) => {
- const { [propertyToRemove]: _, ...newTarget } = target
- return newTarget
- }
- const toto = { a: 55, b: 66 }
- const totoWithoutB = removeProperty(toto, 'b') // { a: 55 }
7.僅當(dāng)對象存在時才向其添加屬性
有時,如果對象已經(jīng)定義了屬性,我們需要向?qū)ο筇砑訉傩裕覀兛赡軙@樣寫:
- const toto = { name: 'toto' }
- const other = { other: 'other' }
- // The condition is not important
- const condition = true
- if (condition) {
- other.name = toto.name
- }
❌不是很好的代碼
✅ 可以用一些更優(yōu)雅的東西!
- const condition = true
- const other = {
- other: 'other',
- ...condition && { name: 'toto' }
- }
8. 使用模板字符串
在 JS 中學(xué)習(xí)字符串時,我們需要將它們與變量連接起來
- const toto = 'toto'
- const message = 'hello from ' + toto + '!' // hello from toto!
如果還有其它變量,我們就得寫很長的表達(dá)式,這時可以使用模板字符串來優(yōu)化。
- const toto = 'toto'
- const message = `hello from ${toto}!` // hello from toto!
9. 條件簡寫
當(dāng)條件為 true 時,執(zhí)行某些操作,我們可能會這樣寫:
- if(condition){
- toto()
- }
這種方式可以用 && 簡寫:
- condition && toto()
10.設(shè)置變量的默認(rèn)值
如果需要給一個變量設(shè)置一個默認(rèn)值,可以這么做:
- let toto
- console.log(toto) //undefined
- toto = toto ?? 'default value'
- console.log(toto) //default value
- toto = toto ?? 'new value'
- console.log(toto) //default value
11.使用 console timer
如果需要知道一個函數(shù)的執(zhí)行時間,可以這么做:
- for (i = 0; i < 100000; i++) {
- // some code
- }
- console.timeEnd() // x ms
作者:CodeOz 譯者:前端小智 來源:dev 原文:https://dev.to/codeoz/improve-your-js-skls-with-theses-tips-52ia