常用功能函数封装

157 阅读1分钟
// 获取设备信息
navigator.userAgent
// 获取url上的参数,转化为对象
const getParamsInUrl = (url = window.location.href) => {
    const q = {};
    url.replace(/([^?&=]+)=([^&#]+)/g, (_, k, v) => (q[k] = v));
    return q;
};
const getParamsInUrl = new URLSearchParams(location.search).get('// 对象的键')
// 判断对象是否为空
const isEmpty = (obj) => Object.keys(obj).length === 0 && obj.constructor === Object;
// 判断是不是安卓
function isAndroid() {
    return /(Android)/i.test(navigator.userAgent);
}
// 判断是不是IOS
function isIOS() {
    return /(iphone|ipad|ipod)/i.test(navigator.userAgent);
}
// 是否微博环境
function isWeibo() {
    return /WeiBo/i.test(navigator.userAgent);
}
// 是否是微信小程序
function isWXMiniProgram() {
    return navigator.userAgent.match(/miniprogram/i) || typeof window.__wxjs_environment !== 'undefined';
}
// 判断是不是微信
function isWeixinBrowser() {
    return /MicroMessenger/i.test(navigator.userAgent);
}
// 动态加载js文件
export const insertScript = (src, option = {}) => {
    const script = document.createElement('script');
    script.src = src;
    Object.keys(option).map((key) => (script[key] = option[key]));
    document.getElementsByTagName('head')[0].appendChild(script);
};
// 设置local
export const setLocalStorage = (key, obj) => {
    if (window.localStorage) {
        window.localStorage.setItem(key, JSON.stringify(obj));
    }
};
// 获取local
export const getLocalStorage = (key) => {
    if (window.localStorage && key) {
        return window.localStorage.getItem(key);
    }
};
// 删除local
export const removeLocalStorage = (key) => {
    if (window.localStorage && key) {
        return window.localStorage.removeItem(key);
    }
    return;
};