判断类型
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));
}