小程序函数全集封装
/** * Created by zrs */ import Vue from 'vue' /** * json拼接为字符串 * @param json * @returns {string} */ export function qs (json) { let str = '' for (let key in json) { if (json.hasOwnProperty(key)) { str += key + '=' + json[key] + '&' } } str = str.substr(0, str.lastIndexOf('&')) return str } /** * 生成指定长度的随机字符 * @param length * @returns {string} */ export function genRandomStr (length) { let arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] let str = '' for (let i = 0; i < length; i++) { str += arr[parseInt(Math.random() * 36)] } return str } /** * 判断字符串是否为手机号 * @param phone * @return {bool} */ export function isPhoneNo (phone) { var reg = /^1\d{10}$/ var flag = reg.test(phone) return flag } /** * 计算日期差 * @param start * @param end * @returns {*} */ export function getDateDiff (start, end) { if (!end) { return '借阅中' } let startTime = new Date(start) let endTime = new Date(end) let time = endTime - startTime let seconds = time / (1000 * 60) let minutes let hours let resultDate = `${seconds}分钟` if (seconds >= 60) { minutes = parseInt(seconds / 60) seconds = seconds % 60 resultDate = `${minutes}小时${seconds}分钟` } if (minutes >= 60) { hours = parseInt(minutes / 60) minutes = minutes % 60 resultDate = `${hours}天${minutes}小时` } return resultDate } /** * 格式化数值为","形式 * @param number * @returns {string} */ export function formatNumber (number) { return String(number).replace(/(\d)(?=(\d{3})+$)/g, '$1,') } /** * 在指定闭区间生成一个随机数 * @param rangeL * @param rangeR */ export function genRandom (rangeL, rangeR) { return parseInt(Math.random() * (rangeR - rangeL + 1) + rangeL) } /** * 将对象转换成数组(类似于map结构) * @param obj * @returns {Array} * @constructor */ export function obj2Array (obj) { let arr = [] for (let key in obj) { if (obj.hasOwnProperty(key)) { let newObj = {} newObj.key = key newObj.value = obj[key] arr.push(newObj) } } return arr } /** * 时间格式化 * @param date 时间对象 * @param fmt 格式:'yyyy-MM-dd hh:mm:ss' * @returns {*} 格式化后的时间 */ export function formatDate (date, fmt) { 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 } /** * 去掉字符串首尾的空格 * @param str */ export function trim (str) { return str.replace(/(^\s*)|(\s*$)/g, '') } /** * 获取字符串的长度 * @param str * @returns {number} */ export function getLength (str) { let len = 0 for (let i = 0; i < str.length; i++) { if (str.charCodeAt(i) > 127 || str.charCodeAt(i) === 94) { len += 2 } else { len += 1 } } return len } /** * 价格校验 * @param price * @returns {Number} 如果是小数,只保留两位小数 */ export function getPrice (price) { if (typeof price !== 'number') { return } if (price <= 0) { return } price += '' let intPart = '' let decPart = '' if (price.indexOf('.') !== -1) { intPart = price.substr(0, price.indexOf('.')) decPart = price.substr(price.indexOf('.') + 1, 2) return parseFloat(intPart + '.' + decPart) } else { return parseFloat(price) } } /** * 正则判断是字符串是否位数字 * @param string * @returns {bool} */ export function isNumber (value) { var patrn = /^(-)?\d+(\.\d+)?$/ if (patrn.exec(value) == null || value === '') { return false } else { return true } } /** * 个性化自定义打印 */ export function customPrint (value) { if (Vue.prototype.$printEnable) { console.log(value); } } /** * 格式化请求url * 将其转换为对象 * 从而直接取各个参数的值 */ export function confirmUrl (url) { var theRequest = {}; if (url.indexOf("?") != -1) { var str = url.substring(url.indexOf("?") + 1); // var str = str.substr(1); var strs = str.split("&"); for (var i = 0; i < strs.length; i++) { theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]); } } return theRequest; }
import http from "./http.js" // 判断数据是否为空 const isEmpty = (obj, desc) => { if (typeof obj == "undefined" || obj == null || obj == "") { if (desc) { toast(desc) } return false; } else { return true; } } // 判断数据是否为空 并弹窗提示 const isEmptyToast = (array) => { array.some(item => { if (typeof item.data == "undefined" || item.data == null || item.data == "") { toast(item.title) return false; } else { return true; } }) } // 验证手机号 const verifyTelPhone = (param) => { if (param == '') { toast('请输入手机号码') return false } else if (!(/^1[3456789]\d{9}$/.test(param))) { toast('请输入正确的手机号码') return false } else { return true } } // 验证验证码号 code 判断是否为6位 const verifyCode = (param) => { if (param == '' || param.length != 6) { toast('请输入正确的验证码') return false } else { return true } } // 验证密码 const verifyPassword = (param) => { if (param.length < 6 || param.length > 12) { toast('请输入6-12位密码') return false } else { return true } } // 验证姓名 2-5个字符 const verifyName = (param) => { if (param.length < 1) { toast('姓名不能少于1个字') return false } else { return true } } // 验证地址 const verifyAddress = (param) => { if (param.length < 5) { toast('详细地址不能少于5个字') return false } else { return true } } /* 弹窗提示 title 弹出信息 icon 图标样式 默认为空 */ const toast = (title, icon) => { uni.showToast({ title, icon: icon || 'none' }) } /* 身份证验证 */ const verifyIDcard = code => { var city = { 11: "北京", 12: "天津", 13: "河北", 14: "山西", 15: "内蒙古", 21: "辽宁", 22: "吉林", 23: "黑龙江 ", 31: "上海", 32: "江苏", 33: "浙江", 34: "安徽", 35: "福建", 36: "江西", 37: "山东", 41: "河南", 42: "湖北 ", 43: "湖南", 44: "广东", 45: "广西", 46: "海南", 50: "重庆", 51: "四川", 52: "贵州", 53: "云南", 54: "西藏 ", 61: "陕西", 62: "甘肃", 63: "青海", 64: "宁夏", 65: "新疆", 71: "台湾", 81: "香港", 82: "澳门", 91: "国外 " }; var tip = ""; var pass = true; if (!code || !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(code)) { tip = "身份证号格式错误"; pass = false; } else if (!city[code.substr(0, 2)]) { tip = "地址编码错误"; pass = false; } else { //18位身份证需要验证最后一位校验位 if (code.length == 18) { code = code.split(''); //∑(ai×Wi)(mod 11) //加权因子 var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]; //校验位 var parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2]; var sum = 0; var ai = 0; var wi = 0; for (var i = 0; i < 17; i++) { ai = code[i]; wi = factor[i]; sum += ai * wi; } var last = parity[sum % 11]; if (parity[sum % 11] != code[17]) { tip = "校验位错误"; pass = false; } } } return pass; } /* 数组去重 */ const unique = data =>{ return Array.from(new Set(data)) } /* baseUrl */ const baseUrl = http.BASE_URL export default{ baseUrl, isEmpty, // 判断是否为空 isEmptyToast, // 判断数据是否为空 并弹窗提示 verifyTelPhone, // 验证手机号 verifyCode, // 验证验证码 verifyPassword, // 验证密码 verifyName, // 验证姓名 verifyAddress, // 验证地址 toast, // 弹窗 verifyIDcard, //验证身份证 unique, //数组去重 }
const dateFormat = (date, format) => { var time = new Date(date * 1000); var y = time.getFullYear(); var month = time.getMonth() + 1; var d = time.getDate(); var h = time.getHours(); var m = time.getMinutes(); var s = time.getSeconds(); month = month < 10 ? ('0' + month) : month; m = m < 10 ? ('0' + m) : m; d = d < 10 ? ('0' + d) : d; s = s < 10 ? ('0' + s) : s; if (format == 'y-m') { return `${y}年${month}月` } else if (format == 'y-m-d') { return `${y}-${month}-${d}` } else { return `${y}-${month}-${d} ${h}:${m}:${s}` } } export { dateFormat }
/** * @param {string} email 邮箱 * @returns {Boolean} */ export function validEmail(email) { const reg = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ return reg.test(email) } /** * @param {string} str 判断字符串 * @returns {Boolean} */ export function isString(str) { if (typeof str === 'string' || str instanceof String) { return true } return false } /** * @param {Array} arg 判断数组 * @returns {Boolean} */ export function isArray(arg) { if (typeof Array.isArray === 'undefined') { return Object.prototype.toString.call(arg) === '[object Array]' } return Array.isArray(arg) }
作者:人参,每篇随笔皆原创(除非注明原作者的随笔),欢迎指正!