一些带有设计模式的优秀代码

1.校验用户名 : 用户名/手机号/邮箱  或者的关系

优秀点:1或者的关系用到了数组的some方法,而不是||.代码简洁性很好; 2 错误优先处理

  handleLogin () {
      // 错误优先
      if (!this.checkAccount() || !this.checkPassword()) return this.$message.error('请输入合法的账号和密码')
      // 数据验证通过的逻辑。。。
    },
    // 校验用户名 : 用户名/手机号/邮箱 或者的关系
    checkAccount () {
      const nameReg = /w{2,20}/
      const phoneReg = /^1[3|4|5|7|8][0-9]{9}$/
      const emailReg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(.[a-zA-Z0-9_-]+)+$/
      const regArr = [nameReg, phoneReg, emailReg]
      // some 数组里面只要有一个满足布尔值就是true  都不满足返回false
      return regArr.some((item) => item.test(this.loginData.account))
    },
    // 校验密码 密码至少包含 数字和英文,长度6-20
    checkPassword () {
      const passReg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/
      return passReg.test(this.loginData.password)
    }

 2.if多条件判断,用数组find 一行代码搞定

  

  function fn () {
    const url = window.location.href
    if (url.includes('a')) return 1
    if (url.includes('b')) return 2
    if (url.includes('c')) return 3
    if (url.includes('d')) return 4
  }
 


function fn1 () { const url = window.location.href const arr = [['a', 1], ['b', 2], ['c', 3], ['d', 4]] // 存放结果值 return arr.find(item => url.includes(item[0]))[1] }

3:棒球比赛

https://leetcode-cn.com/problems/baseball-game/submissions/

原文地址:https://www.cnblogs.com/xiaoliziaaa/p/14336623.html