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

注意: 在实际使用场景中,有些场景对于我们要获取的属性是非必需的,我们可以通过上面这种方式去避免报错出现;但是有些场景下一些属性是必须的,不然就会影响我们的实际功能,这个时候还是尽量给出清晰的报错提示来解决这种错误的出现。

06、检查数组中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

07、数组去重

const fruitList = ['apple', 'mango', 'banana', 'apple'];

const uniqList = [...new Set(fruitList)]
console.log('uniqList:', uniqList); // uniqList: ['apple', 'mango', 'banana']

08、检查是否为数组类型


const fruitList = ['apple', 'mango'];

console.log(typeof fruitList); // object
console.log(Array.isArray(fruiltList)); // true

09、数字&字符串类型转换

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