
在我們的日常開發過程中,我們經常會遇到數字與字元串轉換,檢查對象中是否存在對應值,條件性操作對象資料,過濾數組中的錯誤值,等等這類處理。
在這裡,整理出了一些常用的小技巧,這些技巧是我比較喜歡的,可以使我們的代碼更精簡、更幹淨,且非常實用。
01、通過條件判斷向對象添加屬性
const isValid = false;
const age = 18;
// 我們可以通過展開運算符向對象添加屬性
const person = {
id: 'ak001',
name: 'ak47',
...(isValid && {isActive: true}),
...((age > 18 || isValid) && {cart: 0})
}
console.log('person', person)
02、檢查對象中是否存在某個屬性
const person = {
id: 'ak001',
name: 'ak47'
}
console.log('name' in person); // true
console.log('isActive' in person); // false
03、解構指派
const product = {
id: 'ak001',
name: 'ak47'
}
const { name: weaponName } = product;
console.log('weaponName:', weaponName); // weaponName: ak47
// 通過動态key進行解構指派
const extractKey = 'name';
const { [extractKey]: data } = product;
console.log('data:', data); // data: ak47
04、循環周遊一個對象的key和value
const product = {
id: 'ak001',
name: 'ak47',
isSale: false
}
Object.entries(product).forEach(([key, value]) => {
if(['id', 'name'].includes(key)) {
console.log('key:',key, 'value:',value)
}
})
// key: id value: ak001
// key: name value: ak47
05、使用可選鍊(Optionalchaining)避免通路對象屬性報錯
const product = {
id: 'ak001',
name: 'ak47'
}
console.log(product.sale.isSale); // throw error
console.log(product?.sale?.isSale); // undefined
注意: 在實際使用場景中,有些場景對于我們要擷取的屬性是非必需的,我們可以通過上面這種方式去避免報錯出現;但是有些場景下一些屬性是必須的,不然就會影響我們的實際功能,這個時候還是盡量給出清晰的報錯提示來解決這種錯誤的出現。
6、檢查數組中falsy的值
const fruitList = ['apple', null, 'banana', undefined];
// 過濾掉falsy的值
const filterFruitList = fruitList.filter(Boolean);
console.log('filterFruitList:', filterFruitList);
// filterFruitList:['apple', 'banana']
// 檢查數組中是否有truthy的值
const isAnyFruit = fruitList.some(Boolean);
console.log('isAnyFruit:', isAnyFruit); // isAnyFruit: true
7、數組去重
const fruitList = ['apple', 'mango', 'banana', 'apple'];
const uniqList = [...new Set(fruitList)]
console.log('uniqList:', uniqList); // uniqList: ['apple', 'mango', 'banana']
8、檢查是否為數組類型
const fruitList = ['apple', 'mango'];
console.log(typeof fruitList); // object
console.log(Array.isArray(fruiltList)); // true
9、數字&字元串類型轉換
const personId = '007';
console.log('personId:', +personId, 'type:', typeof +personId);
// personId: 7 type: number
const personId = 119;
console.log('personId:', personId + '', 'type:', typeof (personId + ''));
// personId: 119 type: string
10、巧用空值合并(??)
let data = undefined ?? 'noData;
console.log('data:', data); // data: noData
data = null ?? 'noData';
console.log('data:', data); // data: noData
data = 0 ?? null ?? 'noData';
console.log('data:', data); // data: noData
// 當我們根據變量自身判斷時
data ??= 'noData';
console.log('data:', data); // data: noData
和或(||) 運算符的差別?\
或運算符針對的是falsy類的值 (0,’ ’, null, undefined, false, NaN),而空值合并僅針對null和undefined生效;
11、通過!!進行布爾轉換
console.log('this is not empty:', !!'')
// this is not empty: false
console.log('this is not empty:', !!'Data')
// this is not empty: true
寫在最後
以上就是我今天跟大家分享的11個關于JavaScript的小技巧,希望這些小技巧能夠幫助到你的日常開發工作,如果你覺得有用的話,請點贊我,關注我,并将它分享給你身邊做開發的朋友,也許能夠幫助到他。
最後,感謝你的閱讀。
學習更多技能
請點選下方公衆号