方法

123 阅读1分钟
判断类型
const typeOf = (obj) => obj&&Object.prototype.toString.call(obj).replace(/\[object\s|]/g, '')

在这里插入图片描述

千位符
const milliFormat = num => num && num.toString().replace(/^\d+/g, m => m.replace(/(?=(?!^)(\d{3})+$)/g, ','));

在这里插入图片描述

深度克隆
function deepClone (obj) {  
    if(typeof obj !== "object" && typeof obj !== 'function') {
        return obj;        //原始类型直接返回
    }
    var o = isArray(obj) ? [] : {}; 
    for(i in obj) {  
        if(obj.hasOwnProperty(i)){ 
            o[i] = typeof obj[i] === "object" ? deepClone(obj[i]) : obj[i]; 
        } 
    } 
    return o;
}
解析get请求的url
const parseQueryString = (url) => {
	const index = url.indexOf("?");
	if (index === -1)  return {};
        url = url.substring(index +1);
        let params = {};
        let urlArr = url.split('&');
        for(let item of urlArr) {
            const index = item.indexOf('=');
            const key = item.substring(0, index);
            const value = item.substring(index + 1);
            params[key] = value;
        }
        return params;
     }

在这里插入图片描述

数组去重
const repeat = (arr) =>{
    return arr.sort()
             .join(",,")
             .replace(/(^|,,)([^,]+)(,,\2)*/g, "$1$2")
             .split(",,");
  }
 // 或者
 Array.form(arr);
数组降维
  const arrDrop = (arr) => [].concat.apply([],arr);

在这里插入图片描述

一句话随机排序
const shuffle = arr => arr.sort(() => Math.random() - .5);
带有正则的 if else 优化

一般if else 过长会使用switch,但是switch不知正则(不知道是不是没有找到),推荐使用方法,看着舒服点

const actions = ()=>{ 
	const functionA = ()=> {/*A操作*/} 
	const functionB = ()=>{/*B操作*/} 
	const functionC = ()=>{/*C操作*/} 
	return new Map([
		[/^guest_[1-4]$/,functionA],
		[/^guest_5$/,functionB],
		[/^guest_.*$/,functionC],
		//... ]
	);
}
const onButtonClick = (identity,status)=> {
	let action = [...actions()].filter(([key,value]) => (key.test(`${identity}_${status}`)));
	action.forEach(([key,value])=>value.call(this));
}
react 计算元素的宽度
componentDidMount () {
    const elExcisionWidth = this.elExcision ? Math.ceil(this.elExcision.getBoundingClientRect().width) : 0;
}

render () {
    return <span ref={dom => (this.elExcision = dom)}>/</span>
}