背景
在日常开发中,我们经常会用一些工具类方法来实现业务逻辑 下面列举几种最常用的
URL截取参数
//直接调用输入想要截取的参数名称几个
export function getParamFromUrl(key) {
if (key === undefined) return null;
let search = location.search.substr(1);
let mReg = new RegExp('(^|&)' + key + '=([^&]*)(&|$)');
let mValue = search.match(mReg);
if (mValue != null) return unescape(mValue[2]);
return null;
}
//示例
let city = getParamFromUrl('city');
JSON是否为空判断
//输入想要检测的json数据 如果为空返回返回false
export function isNullObject(model) {
if (typeof model === "object") {
let hasProp = false;
for (const prop in model) {
hasProp = true;
break;
}
if (hasProp) {
return false;
}
return true;
} else {
throw "model is not object";
}
}
数据类型检测
//检测变量的数据类型
export function getParamType(item) {
if (item === null) return null;
if (item === undefined) return undefined;
return Object.prototype.toString.call(item).slice(8, -1);
}
//返回String Function Boolean Object Number
获取cookie
//获取document下cookie的具体某个参数值
export function getCookie(key) {
if (key === undefined) {
return undefined;
}
let cookies = document.cookie;
let mReg = new RegExp('(^|;)\\s*' + key + '=([^;]*)(;|$)');
let mValue = cookies.match(mReg);
let ret = undefined;
if (mValue != null) {
ret = unescape(mValue[2]);
}
if (ret !== undefined) {
ret = ret.replace(/^\"|\'/i, '').replace(/\"|\'$/i, '');
}
return ret;
}
版本号对比
一般在做APP端开发的时候需要用到一些版本控制,那么就需要针对版本号来进行对比,高版本或者低版本做一些特殊的逻辑处理,下面就是提供版本对比的方法
//传入要对比的版本号,一般前面一个传入当前的版本号,后面一个写上要对比的版本号
export function versionCompare(higher, lower) {
let sep = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '.';
let higherAry = higher.split(sep),
lowerAry = lower.split(sep);
let l = Math.max(higherAry.length, lowerAry.length);
for (let i = 0; i < l; i++) {
let high = parseInt(higherAry[i] || 0);
let low = parseInt(lowerAry[i] || 0);
if (high > low) {
return 1;
}
if (high < low) {
return -1;
}
}
return 0;
}
//返回值 higher > lower: 1;higher = lower: 0;higher < lower:-1
数组去重
export function arrayUniq(array){
let temp = [];
for(let i = 0; i < array.length; i++){
if(temp.indexOf(array[i]) == -1){
temp.push(array[i]);
}
}
return temp;
}
iPhone X系列机型判断
export function isIphoneX() {
// iPhone X、iPhone XS
let isIPhoneX =
/iphone/gi.test(window.navigator.userAgent) &&
window.devicePixelRatio &&
window.devicePixelRatio === 3 &&
window.screen.width === 375 &&
window.screen.height === 812;
// iPhone XS Max
let isIPhoneXSMax =
/iphone/gi.test(window.navigator.userAgent) &&
window.devicePixelRatio &&
window.devicePixelRatio === 3 &&
window.screen.width === 414 &&
window.screen.height === 896;
// iPhone XR
let isIPhoneXR =
/iphone/gi.test(window.navigator.userAgent) &&
window.devicePixelRatio &&
window.devicePixelRatio === 2 &&
window.screen.width === 414 &&
window.screen.height === 896;
if (isIPhoneX || isIPhoneXSMax || isIPhoneXR) {
return true;
}
return false;
}
浏览器内核检测
export function checkBrowser() {
const u = navigator.userAgent;
const obj = {
trident: u.indexOf("Trident") > -1, //IE内核
presto: u.indexOf("Presto") > -1, //opera内核
webKit: u.indexOf("AppleWebKit") > -1, //苹果、谷歌内核
gecko: u.indexOf("Gecko") > -1 && u.indexOf("KHTML") == -1, //火狐内核
}
return Object.keys(obj)[Object.values(obj).indexOf(true)];
}
localStorage相关处理
//localStorage取值
export function getLocalStorageItem(key) {
return localStorage.getItem(key);
}
//localStorage存值
export function setLocalStorageItem(key, value) {
if (typeof (value) === 'object') value = JSON.stringify(value);
localStorage.setItem(key, value);
}
//localStorage删除值
export function removeLocalStorageItem(key) {
return localStorage.removeItem(key);
}
时间格式化
export function getFillDate(key) {
if(key < 10) {
return `0${key}`;
}else{
return `${key}`;
}
}
/**
* 时间戳转化为年月日
* @param times 时间戳
* @param ymd 格式类型(yyyy-mm-dd,yyyy/mm/dd)
* @param hms 可选,格式类型(hh,hh:mm,hh:mm:ss)
* @returns {年月日}
*/
export function dateFomat (times, ymd, hms) {
const oDate = new Date(times)
const oYear = oDate.getFullYear()
const oMonth = oDate.getMonth() + 1
const oDay = oDate.getDate()
const oHour = oDate.getHours()
const oMin = oDate.getMinutes()
const oSec = oDate.getSeconds()
let oTime // 最后拼接时间
// 年月日格式
switch (ymd) {
case 'yyyy-mm-dd':
oTime = oYear + '-' + getFillDate(oMonth) + '-' + getFillDate(oDay)
break
case 'yyyy/mm/dd':
oTime = oYear + '/' + getFillDate(oMonth) + '/' + getFillDate(oDay)
break
}
// 时分秒格式
switch (hms) {
case 'hh':
oTime = oTime + ' ' + getFillDate(oHour)
break
case 'hh:mm':
oTime = oTime + ' ' + getFillDate(oHour) + ':' + getFillDate(oMin)
break
case 'hh:mm:ss':
oTime = oTime + ' ' + getFillDate(oHour) + ':' + getFillDate(oMin) + ':' + getFillDate(oSec)
break
}
return oTime
}
JSON转URL参数
export function paramsToUrlQuery(params) {
let types = Object.prototype.toString.call(params).slice(8, -1);
if (types === 'Object') {
let tempArr = [];
for (let i in params) {
let key = encodeURIComponent(i);
let value = encodeURIComponent(params[i]);
tempArr.push(key + '=' + value);
}
let urlParamsStr = tempArr.join('&');
return urlParamsStr;
} else {
throw 'model is not object';
}
}
删除url指定参数
export function delUrlParam(url, key) {
let baseUrl = url.split('?')[0] + '?';
let query = url.split('?')[1];
if (query.indexOf(key) > -1) {
let obj = {};
let arr = query.split('&');
for (let i = 0; i < arr.length; i++) {
arr[i] = arr[i].split('=');
obj[arr[i][0]] = arr[i][1];
}
delete obj[key];
let url =
baseUrl +
JSON.stringify(obj)
.replace(/[\"\{\}]/g, '')
.replace(/\:/g, '=')
.replace(/\,/g, '&');
return url;
} else {
return url;
}
}
获取url全部参数转json
export function getAllUrlParamsToJson (url) {
let urlRes = url ? url : window.location.href;
let _pa = urlRes.substring(urlRes.indexOf('?') + 1),
_arrS = _pa.split('&'),
_rs = {};
for (let i = 0, _len = _arrS.length; i < _len; i++) {
let pos = _arrS[i].indexOf('=');
if (pos == -1) {
continue;
}
let name = _arrS[i].substring(0, pos),
value = window.decodeURIComponent(_arrS[i].substring(pos + 1));
_rs[name] = value;
}
return _rs;
}
去除字符串空格
/**
* @description 去除空格
* @param { string } str 待处理字符串
* @param { number } type 去除空格类型 1-所有空格 2-前后空格 3-前空格 4-后空格 默认为1
*/
export function trim(str, type = 1) {
if (type && type !== 1 && type !== 2 && type !== 3 && type !== 4) return;
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;
}
}