js 代码优化

29 阅读2分钟

求数组的最大值与最小值

Math.min(...array)
Math.max(...array)

过滤错误值

const array = [1, 0, undefined, 6, 7, '', false];
array.filter(Boolean);

判断简化

if(a === undefined || a === 10 || a=== 15 || a === null) {
    //...
}
if([undefined, 10, 15, null].includes(a)) {
    //...
}

清空数组

let array = ["A", "B", "C", "D", "E", "F"]
array.length = 0 
console.log(array)  // []

对象(数组)验证方式

parent?.child?.child1?.child2
//可选链同样适用于数组
const array = [1, 2, 3];
array?.[5]

优化if/else

//小白写法
const onButtonClick = (status, identity) => {
  if (identity == 'guest') {
    if (status == 1) {
      //函数处理
    } else if (status == 2) {
      //函数处理
    } else if (status == 3) {
      //函数处理
    } else if (status == 4) {
      //函数处理
    } else if (status == 5) {
      //函数处理
    } else {
      //函数处理
    }
  } else if (identity == 'master') {
    if (status == 1) {
      //函数处理
    } else if (status == 2) {
      //函数处理
    } else if (status == 3) {
      //函数处理
    } else if (status == 4) {
      //函数处理
    } else if (status == 5) {
      //函数处理
    } else {
      //函数处理
    }
  }
}
//进阶写法
//利用数组循环的特性,符合条件的逻辑都会被执行,那就可以同时执行公共逻辑和单独逻辑。
const functionA = ()=>{/*do sth*/}       // 单独业务逻辑
const functionB = ()=>{/*do sth*/}       // 单独业务逻辑
const functionC = ()=>{/*send log*/}   // 公共业务逻辑
const actions = new Map([
    ['guest_1', () => { functionA }],
    ['guest_2', () => {  functionB }],
    ['guest_3', () => { functionC }],
    ['guest_4', () => { functionA }],
    ['default', () => { functionC  }],
    //...
])
/**
 * 按钮点击事件
 * @param {string} identity 身份标识:guest客态 master主态
  * @param {number} status 活动状态:1开票中 2开票失败 3 开票成功 4 商品售罄 5 有库存未开团
 */
const onButtonClick = (identity, status) => {
  let action = actions.get(`${identity}_${status}`) || actions.get('default')
  action.call(this)
}

有条件的对象属性

nst getUser = (emailIncluded) => {
  return {
    name: 'John',
    surname: 'Doe',
    ...emailIncluded && { email : 'john@doe.com' }
  }
}
const user = getUser(true);
console.log(user); // outputs { name: "John", surname: "Doe", email: "john@doe.com" }
const userWithoutEmail = getUser(false);
console.log(userWithoutEmail); // outputs { name: "John", surname: "Doe" }

传参最好传对象,不要传数组

解构对象技巧

//ES6的解构赋值虽然好用。但是要注意解构的对象不能为undefined、null。否则会报错,故要给被解构的对象一个默认值。
const {a,b,c,d,e} = obj || {};

关于if中判断条件

if(
    type == 1 ||
    type == 2 ||
    type == 3 ||
    type == 4 ||
){
   //...
}
const condition = [1,2,3,4];

if( condition.includes(type) ){
   //...
}

关于输入框非空的判断

if(value !== null && value !== undefined && value !== ''){
    //...
}
if((value??'') !== ''){
  //...
}