In our daily development process, we often encounter numbers and strings conversion, check whether there is a corresponding value in an object, conditionally manipulate object data, filter error values in an array, and so on.
Here, I have sorted out some commonly used tips. These tips are my favorite ❤️, which can make our code leaner, cleaner, and very practical.
- Add properties to objects by conditional judgment
const isValid = false;
const age = 18;
// 我们可以通过展开运算符向对象添加属性
const person = {
id: 'ak001',
name: 'ak47',
...(isValid && {isActive: true}),
...((age > 18 || isValid) && {cart: 0})
}
console.log('person', person)
- Check if a property exists in an object
const person = {
id: 'ak001',
name: 'ak47'
}
console.log('name' in person); // true
console.log('isActive' in person); // false
- destructuring assignment
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
- Loop through the keys and values of an object
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
- Use optional chaining to avoid errors when accessing object properties
const product = {
id: 'ak001',
name: 'ak47'
}
console.log(product.sale.isSale); // throw error
console.log(product?.sale?.isSale); // undefined
Note⚠️: In actual usage scenarios, some scenarios are not necessary for the properties we want to obtain, we can avoid errors by the above method; but in some scenarios, some properties are required, otherwise it will affect our actual function, at this time, try to give a clear error message to solve this kind of error.
6. Check the value of falsy in the array
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. Array deduplication
const fruitList = ['apple', 'mango', 'banana', 'apple'];
const uniqList = [...new Set(fruitList)]
console.log('uniqList:', uniqList); // uniqList: ['apple', 'mango', 'banana']
- Check if it is an array type
const fruitList = ['apple', 'mango'];
console.log(typeof fruitList); // object
console.log(Array.isArray(fruiltList)); // true
9. Number & String Type Conversion
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
- Clever use of null value coalescing (??)
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: 0
// 当我们根据变量自身判断时
data ??= 'noData';
console.log('data:', data); // data: noData
Difference between and or (||) operator? \
The OR operator is for falsy values (0,' ', null, undefined, false, NaN), while null coalescing only works for null and undefined;
- Boolean conversion via !!
console.log('this is not empty:', !!'')
// this is not empty: false
console.log('this is not empty:', !!'Data')
// this is not empty: true
Finally, I hope these little tips can help you in your daily development. If you have a better way, please leave a message to share 😊
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。