美文网首页
前端常用方法

前端常用方法

作者: O蚂蚁O | 来源:发表于2019-08-21 17:32 被阅读0次

    时间格式化

      const dateFormatter = (formatter, date) => {
        date = (date ? new Date(date) : new Date)
        const Y = date.getFullYear() + '',
              M = date.getMonth() + 1,
              D = date.getDate(),
              H = date.getHours(),
              m = date.getMinutes(),
              s = date.getSeconds()
        return formatter.replace(/YYYY|yyyy/g, Y)
                        .replace(/YY|yy/g, Y.substr(2, 2))
                        .replace(/MM/g, (M < 10 ? '0' : '') + M)
                        .replace(/DD/g, (D < 10 ? '0' : '') + D)
                        .replace(/HH|hh/g, (H < 10 ? '0' : '') + H)
                        .replace(/mm/g, (m < 10 ? '0' : '') + m)
                        .replace(/ss/g, (s < 10 ? '0' : '') + s)
    }
    
    dateFormatter('YYYY-MM-DD HH:mm', '1995/02/15 13:55') // 1995-02-15 13:55
    

    生成随机UID

    const genUid = () => {
      var length = 20
      var soupLength = genUid.soup_.length
      var id = []
      for (var i = 0; i < length; i++) {
        id[i] = genUid.soup_.charAt(Math.random() * soupLength)
      }
      return id.join('')
    }
    genUid.soup_ = '!#$%()*+,-./:;=?@[]^_`{|}~ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
    genUid() // ;l`yCPc9A8IuK}?N6,%}
    

    一行代码去重数组

    const list = [1, 1, 2, 3, 6, 45, 8, 5, 4, 6, 5]
    const uniqueList = [...new Set(list)] // [1, 2, 3, 6, 45, 8, 5, 4]
    

    相关文章

      网友评论

          本文标题:前端常用方法

          本文链接:https://www.haomeiwen.com/subject/tasisctx.html