常见的js封装

65 阅读1分钟

1、随机生成随机颜色

const randomHexColor = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`
console.log(randomHexColor());

2、判断是ios还是android还是web

const isDevice = function() { // 判断是android还是ios还是web
var ua = navigator.userAgent.toLowerCase()
if (ua.match(/iPhone\sOS/i) === 'iphone os' || ua.match(/iPad/i) === 'ipad') { // ios
  return 'iOS'
}
 if (ua.match(/Android/i) === 'android') {
  return 'Android'
 }
 return 'Web'
}

3、判断是否为微信

const isWx = function() { // 判断是否为微信
 var ua = window.navigator.userAgent.toLowerCase()
 if (ua.match(/MicroMessenger/i) === 'micromessenger') {
  return true
 }
 return false
}

4、本地存储 (vue)

const storage = {
  setItem(key, value) {
   localStorage.setItem(key, JSON.stringify(value))
  },
  getItem(key) {
   return JSON.parse(localStorage.getItem(key))
  },
  remove(key) {
   localStorage.removeItem(key)
  },
  clear() {
   localStorage.clear()
  }
}
export default storage

5、判断是否是字符串

export function isString(str) {
  return typeof str === 'string' || str instanceof String
}

6、判断是否是数组

export function isArray(arg) {
 if (typeof Array.isArray === 'undefined') {
  return Object.prototype.toString.call(arg) === '[object Array]'
 }
 return Array.isArray(arg)
}

7、去除空格

const trim = function(str, type) { // 去除空格, type: 1-所有空格 2-前后空格 3-前空格 4-后空格
    type = type || 1
    switch (type) {
    case 1:
    return str.replace(/\s+/g, '')
    case 2:
    return str.replace(/(^\s*)|(\s*$)/g, '')
    case 3:
    return str.replace(/(^\s*)/g, '')
    case 4:
    return str.replace(/(\s*$)/g, '')
    default:
    return str
   }
}

8、时间格式化

const formatDate = function(fmt, date) { // 时间格式化 【'yyyy-MM-dd hh:mm:ss',时间】

 if (typeof date !== 'object') {
  date = !date ? new Date() : new Date(date)
 }
 var o = {

 'M+': date.getMonth() + 1, // 月份
 'd+': date.getDate(), // 日
 'h+': date.getHours(), // 小时
 'm+': date.getMinutes(), // 分
 's+': date.getSeconds(), // 秒
 'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
 'S': date.getMilliseconds() // 毫秒
}
if (/(y+)/.test(fmt)) {
 fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
}
for (var k in o) {
 if (new RegExp('(' + k + ')').test(fmt)) {
 fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
 }
}
return fmt
}