obj赋值参数
/**
* obj赋值操作
* @param {Object} obj1
* @param {Object} obj2
* @returns {Object}
*/
export const objAssignFn = (obj1, obj2) => {
for (const key in obj1) {
obj1[key] = obj2[key];
}
return obj1;
};
字符串高亮
/**
* 高亮
* @param {String} str
* @param {Array[Object]} indexArr 索引对象数组
* @returns {String}
*/
export const replaceStr = (str, indexArr) => {
let strArr = [];
indexArr &&
indexArr.forEach((item) => {
strArr.push(str.substr(item.startIndex, item.length));
});
strArr.forEach((item) => {
str = str.replace(
item,
`<span style="color:red;font-weight:900;">${item}</span>`
);
});
return str;
};
深层次获取obj值
function lookup(obj, keyName) {
//首先判断keyName是否含有.
if (keyName.indexOf('.') != -1 && keyName != '.') {
//有就拆分
let keys = keyName.split(".");
let temp = obj;
for (let i=0; i < keys.length; i++) {
//逐渐访问
temp = temp[keys[i]];
}
//循环结束后返回temp
return temp;
}
//没有. 就直接使用
return obj[keyName];
}
//下面是试用一下这个函数是否可行?
var obj = {
a:{
c:{
d:123
}
}
}
lookup({a:{c:{d:123}}},'a.c.d') //123
防抖
const debounce = function (fn, delay = 500) {
let timer
return function (...args) {
if(timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
fn.apply(this,args)
},delay)
}
};
let input = document.getElementById("input");
const change = debounce(() => {
console.log(input.value);
}, 1000);
生成指定范围随机数
/**
* @desc 生成随机数
* @param {number} min
* @param {number} max
* @return {number} res
*/
const getRandom = (min, max) => {
return Math.floor(Math.random() * (max - min + 1) + min)
};
判断数据类型
/**
* @desc 判断类型,返回实例'Number'
* @param {String,Array....} obj
*/
const typeOf = (obj) => {
return Object.prototype.toString.call(obj).slice(8,-1)
}
//改进版--进行比对,返回boolean
const isType = (val, type) => {
return Object.prototype.toString.call(val).slice(8, -1) === type;
};
URL参数转对象
/**
* @desc 获取url参数
* @param {String} prop
* @return {Object}
*/
const getUrlParams = (prop) => {
let params = {},
query = location.search.substring(1),
arr = query.split('&'),
rt;
for (let i = 0, len = arr.length; i < len; i++) {
let item = arr[i],
tmp = item.split('='),
key = tmp[0],
val = tmp[1];
if (typeof params[key] == 'undefined') {
params[key] = val
} else if (typeof params[key] == 'string') {
params[key] = [params[key], val]
} else {
params[key].push(val)
}
}
rt = prop ? params[prop] : params
return rt
}
对象序列化
/**
* @desc 对象序列化
* @param {Object} obj
* @return {String}
*/
const stringfyQs = (obj) => {
if (!obj) return ''
let pairs = []
for (let key in obj) {
let value = obj[key]
if (value instanceof Array) {
for (var i = 0; i < value.length; ++i) {
pairs.push(encodeURIComponent(key + '[' + i + ']') + '=' + encodeURIComponent(value[i]))
}
continue
}
pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]))
}
return pairs.join('&')
}
是否是微信浏览器
/**
* @desc 是否微信内置浏览器
* @return {Boolean}
*/
const isWeixin = () => {
const ua = navigator.userAgent.toLowerCase();
if (ua.match(/MicroMessenger/i) == 'micromessenger') {
return true
} else {
return false
}
}
获取设备类型
/**
* @desc 获取操作系统类型
* @return {String}
*/
const mobileType = () => {
let u = navigator.userAgent
let isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1 //android终端
let isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) //ios终端
if (isAndroid) {
return 'android'
} else if (isiOS) {
return 'iphone'
}
}
是否是手机
/**
* @desc 判断是手机吗
* @return {String}
*/
const getOs = () => {
let sUserAgent = navigator.userAgent.toLowerCase();
let bIsIpad = sUserAgent.match(/ipad/i) == 'ipad'
let bIsIphoneOs = sUserAgent.match(/iphone os/i) == 'iphone os'
let bIsMidp = sUserAgent.match(/midp/i) == 'midp'
let bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) == 'rv:1.2.3.4'
let bIsUc = sUserAgent.match(/ucweb/i) == 'ucweb'
let bIsAndroid = sUserAgent.match(/android/i) == 'android'
let bIsCE = sUserAgent.match(/windows ce/i) == 'windows ce'
let bIsWM = sUserAgent.match(/windows mobile/i) == 'windows mobile'
if (bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM) {
return 'mobile'
} else {
return 'web'
}
}
存储
export const setLocal = (key, val) => {
window.localStorage.setItem(key, JSON.stringify(val));
};
export const getLocal = (key) => {
return JSON.parse(window.localStorage.getItem(key));
};
export const removeLocal = (key) => {
window.localStorage.removeItem(key);
};
//进阶版
/**
* @desc localStroge/sessionStroge缓存
* @param {String} key 键名
* @param {String} val 键值
* @param {Date} time 过期时间
*/
const localStorageApi = {
// time有效期 默认是半小时传入ms
set: function (key, val, time = +new Date() + 0.5 * 3600 * 1000) {
let cacheVal = {
val: val,
exp: time
}
localStorage.setItem(key, JSON.stringify(cacheVal))
},
get: function (key) {
let cacheVal = localStorage.getItem(key)
if (!cacheVal) return ''
let result = JSON.parse(cacheVal)
if (+new Date() > result.exp) { //缓存过期
this.remove(key)
return ''
}
return result.val
},
remove: function (key) {
localStorage.removeItem(key)
},
clear: function () {
localStorage.clear()
}
}