1、随机生成随机颜色
const randomHexColor = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`
console.log(randomHexColor());
2、判断是ios还是android还是web
const isDevice = function() {
var ua = navigator.userAgent.toLowerCase()
if (ua.match(/iPhone\sOS/i) === 'iphone os' || ua.match(/iPad/i) === 'ipad') {
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 = 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) {
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
}