前端代码简洁方案

1.条件语句使用Object

const actions = {
  1: 'processing',
  2: 'fail',
  3: 'success',
  4: 'cancel',
  5:funtion(){
      console.log('你好啊,我是5')
  }
  default: 'other',
};

console.log(actions[status] ?? actions.default);
//??  (空值合并运算符)   当左边为null和undefined

2.使用声明式

//声明式:筛选我需要的结果 (推荐)
const result=dataSource.filter((item)=>{item.age>10})

//命令式:亲历而为查找/追加数据
let result=[]
dataSource.forEach((item)=>{
    if(item.age>10){
       result.push(item)
    }
})

3.给定默认值

1.函数


function handler(config){
   config.map((item)=>{
       item.content=Number(item.comtent)
   })
}
//如果忘记传递参数,浏览器会报错

//解决办法,给默认值:
function handler(config=[]){
   config.map((item)=>{
       item.content=Number(item.comtent)
   })
}

2.解构赋值

//数组解构给定默认值
function handleArr(arr) {
    let [a, b, c] = [1, 2, 3]
    return a + b + c    
}

//当我们不确定结构的数组时,可以给定默认值

function handleArr(arr){
    let [a=1,b=2,c=3]=arr     //a,b,c给定默认值
    return a+b+c
}
const arr=[1,2]
handlerArr(arr)
//对象解构给定默认值
function handleObj(obj) {
  const { name, list = [] } = obj //给定默认值,提高代码健壮性
  if(name) {
    list.map((item) => {
      console.log(item)
    })
  }
}

const obj = {
  name: 'add1',
  list: [1, 2, 3]
}

//接口返回,提前给定默认值防止出错

async function handleData() {
  const { code, msg, data = [] }  = await fetchList() //防止返回出错,给定默认值空数组
  //防止返回不是data,类型检查
  Array.isArray(data) && data.map((item) => {
    console.log(item)
  })
}

4.includes优化代码

//普通实现  ||
function verifyIdentity(identityId){
    if(identityId==1 || identityId==2 || identityId==3 || identityId==4){
        return '你的身份合法,请通行!'
    }else{
        return '你的身份未知,警告!'
    }
}

//初级优化
function verifyIdentity(identityId){
    if([1,2,3,4].includes(identityId)){
        return '你的身份合法,请通行!'
    }else{
        return '你的身份未知,警告!'
    }
}

//includes+三元优化
function verifyIdentity(identityId){
    return [1,2,3,4].includes(identityId)?'你的身份合法,请通行!':'你的身份未知,警告!'
}

5.if else语句

1.单个if else优化

//优化前
let flag = true
if(flag){
    //执行业务逻辑
}else{
    return;
}

//优化后   先排除false情形,通过则后面执行true情形的业务逻辑
let flag = true

if(!flag)return;

//执行业务逻辑


或者:
flag && callMethod()   //变量为true才执行后续操作

2.单个if else带返回值优化

//优化前
function demo(flag){
    if(flag){
        return "真"
    }else{
        return "假"
    }
}


//优化后
function demo(flag){
    return flag? "真" : "假"
}

3.单个 if else 执行不同方法 优化 同上


function success(){
    console.log("success")
}

function fail(){
    console.log("fail")
}

//优化前
function demo(flag){
    if(flag){
        success()
    }else{
        fail()
    }
}

//优化后
function demo(flag){
    flag?success():fail()
}

//深层次优化

// 如果你不能保证 你所传的参数一定是布尔值的话 用这种
function demo(flag){
    [false,true].includes(flag) && [fail,success][Number(flag)]()
}

// false 转成 0 ,对应执行success ,true 转成 1,对应执行 fail

// 如果你能保证 你所传的参数一定是布尔值的话 用这种
function demo(flag){
    [fail,success][Number(flag)]()
}

4.多个if else嵌套优化

//场景:后端大哥说了,给你返回的数据里面的 如果有 userInfo字段,并且userInfo下面有hobby字段并且有值就显示 hobby里面的内容,否则页面 hobby这一块不显示

let result = {
    status:200,
    codeMsg:'success',
    data:{
        userInfo:{
            age:18,
            hobby:['敲代码','打篮球']
        }
    }
}


//成功拿到数据了 result      (第一种优化)
if ( result.data && result.data.userInfo && 
    result.data.userInfo.hobby && 
    Array.isArray(result.data.userInfo.hobby) && 
    result.data.userInfo.hobby.length ) 
{
    //遍历 result.data.userInfo.hobby 进行渲染显示
}


//成功拿到数据了 result   (第二种优化)
result.data && 
result.data.userInfo && 
result.data.userInfo.hobby && 
Array.isArray(result.data.userInfo.hobby) && 
result.data.userInfo.hobby.length) &&
(()=>{
    //遍历 result.data.userInfo.hobby 进行渲染显示
})()


//成功拿到数据了 result   (第三种优化 采用try catch策略)
try {
   if(result.data.userInfo.hobby.length){
       //遍历 result.data.userInfo.hobby 进行渲染显示
   }
} catch (error) {
   
}


//第四种优化              (新特性  链式判断)
if(result?.data?.userInfo?.hobby?.length){
    //遍历 result.data.userInfo.hobby 进行渲染显示
}


5.多个if else带返回值 优化

//优化前
function getPosition(direction){
    if(direction == "left"){
        return "左"
    }else if(direction == "right"){
        return "右"
    }else if(direction == "top"){
        return "上"
    }else if(direction == "bottom"){
        return "下"
    }else{
        return "未知"
    }
}

//优化后
function getPosition(direction){
    return ({
        left:"左",
        right:"右",
        top:"上",
        bottom:"下"
    })[direction] || "未知"
}

//策略模式优化
const directions=new Map([
    ['left','左'],
    ['right','右'],
    ['top','上'],
    ['bottom','下'],
])

const getPosition(direction)=>{
    return directions.get(direction)||'未知'
}

分支优化

1.简单分支优化

function getUserDescribe(name) {
    const describeForNameMap = {
        小刘: () => console.log("刘哥哥"),
        小红: () => console.log("小红妹妹"),
        陈龙: () => console.log("大师"),
        李龙: () => console.log("师傅"),
        大鹏: () => console.log("恶人"),
    };
    describeForNameMap[name] ? describeForNameMap[name]() : console.log("此人比较神秘!");
}

2.复杂分支优化

function getUserDescribe(name) {
    const describeForNameMap = [
        [
            (name) => name.length > 3, // 判断条件
            () => console.log("名字太长") // 执行函数
        ],
        [
            (name) => name.length < 2, 
            () => console.log("名字太短")
        ],
        [
            (name) => name[0] === "陈", 
            () => console.log("小陈")
        ],
        [
            (name) => name === "大鹏", 
            () => console.log("管理员")
        ],
        [
            (name) => name[0] === "李" && name !== "李鹏",
            () => console.log("小李"),
        ],
    ];
    // 获取符合条件的子数组
    const getDescribe = describeForNameMap.find((item) => item[0](name));
    // 子数组存在则运行子数组中的第二个元素(执行函数)
    getDescribe ? getDescribe[1]() : console.log("此人比较神秘!");
}

getUserDescribe('齐天大圣')()   //符合第一个条件分支,输出名字太长

3.抽离分支

const describeForNameMap = {
    小刘: () => console.log("刘哥哥"),
    小红: () => console.log("小红妹妹"),
    陈龙: () => console.log("大师"),
    李龙: () => console.log("师傅"),
    大鹏: () => console.log("恶人"),
};

function getUserDescribe(name) {
    describeForNameMap[name] ? describeForNameMap[name]() : console.log("此人比较神秘!");
}
const describeForNameMap = [
    [
        (name) => name.length > 3, // 判断条件
        () => console.log("名字太长") // 执行函数
    ],
    [
        (name) => name.length < 2, 
        () => console.log("名字太短")
    ],
    [
        (name) => name[0] === "陈", 
        () => console.log("小陈")
    ],
    [
        (name) => name === "大鹏", 
        () => console.log("管理员")
    ],
    [
        (name) => name[0] === "李" && name !== "李鹏",
        () => console.log("小李"),
    ],
];
    
function getUserDescribe(name) {
    // 获取符合条件的子数组
    const getDescribe = describeForNameMap.find((item) => item[0](name));
    // 子数组存在则运行子数组中的第二个元素(执行函数)
    getDescribe ? getDescribe[1]() : console.log("此人比较神秘!");
}

switch语句


switch(type){
        //当type为'A'或'B'
    case 'A':
        console.log(1)
        break
    case 'B':
        console.log(2)
        break
    case 'C':
        conlose.log(3)
        break;
    default:
        console.log(0)
}

console.log优化

console.log('name', name)
//可以写成
console.log({name})

隐式转换

// 字符串转数字代码对比 

const price = parseInt('32'); //传统方式
const price = Number('32'); //传统方式

const price = +'32'; //新方式

// 日期转换为时间戳代码对比 

const timeStamp = new Date().getTime(); //传统方式
const timeStamp = +new Date(); //新方式

//布尔转数字新方式
 console.log(+true); // Return: 1
 console.log(+false); // Return: 0


// 各种类型转布尔代码对比 

const isTrue = Boolean('') //传统方式
const isTrue = !!'' //新方式

const isTrue = Boolean(0) //传统方式
const isTrue = !!0 //新方式

const isTrue = Boolean(null) //传统方式
const isTrue = !!null //新方式

const isTrue = Boolean(undefined) //传统方式
const isTrue = !!undefined //新方式

// 数字转string代码对比
const num = 1;

const str = num.toString(); //传统方式
const str = num + ''; //新方式


vue中优化

1.v-if 多条件判断

普通写法 v-if="condition === 0 || condition === 1 || condition === 2"
简洁写法 v-if="[0, 1, 2].includes(condition)"   <!--括号里可以是字符串和数字-->

2.不要在template中写很长的判断、运算,可以使用计算属性computed

//反例:
<div>
    {{
  fullName.split(' ').map(function (word) {
    return word[0].toUpperCase() + word.slice(1)
  }).join(' ')
}}
</div>

//推荐:
<!-- 在模板中 -->
<div>{{ normalizedFullName }}</div>
// 复杂表达式已经移入一个计算属性
computed: {
  normalizedFullName: function () {
    return this.fullName.split(' ').map(function (word) {
      return word[0].toUpperCase() + word.slice(1)
    }).join(' ')
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值