文章目录
- 1. Array
- 2. String
- 3. Number
- 4. Object
- 5. Function
- 6. Browser
- 6.1 isMobile: 判断设备是否是移动端
- 6.2 isMac: 判断系统是否是mac
- 6.3 isWindows: 判断系统是否是mac
- 6.4 whatOS: 判断当前的操作系统
- 6.5 getBrowserClass: 获取浏览器类型
- 6.6 hide:隐藏所有的指定标签
- 6.7 CopyToClipboard: 复制到剪切板
- 6.8 GetParamByName: 获取url参数
- 6.9 currentURL:返回当前链接url
- 6.10 bottomVisible:检查页面底部是否可见
- 6.11 insertAfter:在指定元素之后插入新元素
- 6.12 insertBefore:在指定元素之前插入新元素
- 6.13 nodeListToArray:转换nodeList为数组
- 6.14 randomHexColorCode:随机十六进制颜色
- 6.15 ScrollToTop: 滚动到顶部
- 6.9 smoothScroll:滚动到指定元素区域
1. Array
1.1 all:布尔全等判断
const all = (arr, fn = Boolean) => arr.every(fn);
all([4, 2, 3], x => x > 1); // true
all([1, 2, 3]); // true
1.2 allEqual:检查数组各项相等
const allEqual = arr => arr.every(val => val === arr[0]);
allEqual([1, 2, 3, 4, 5, 6]); // false
allEqual([1, 1, 1, 1]); // true
1.3 approximatelyEqual:约等于
const approximatelyEqual = (v1, v2, epsilon = 0.001) => Math.abs(v1 - v2) < epsilon;
approximatelyEqual(Math.PI / 2.0, 1.5708); // true
1.4 average:平均数
const average = (...nums) => nums.reduce((acc, val) => acc + val, 0) / nums.length;
average(...[1, 2, 3]); // 2
average(1, 2, 3); // 2
1.5 averageBy:数组对象属性平均数
此代码段将获取数组对象属性的平均值
const averageBy = (arr, fn) =>
arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val) => acc + val, 0) /
arr.length;
averageBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], o => o.n); // 5
averageBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n'); // 5
1.6 castArray:其它类型转数组
const castArray = val => (Array.isArray(val) ? val : [val]);
castArray('foo'); // ['foo']
castArray([1]); // [1]
castArray(1); // [1]
1.7 compact:去除数组中的无效/无用值
const compact = arr => arr.filter(Boolean);
compact([0, 1, false, 2, '', 3, 'a', 'e' * 23, NaN, 's', 34]);
// [ 1, 2, 3, 'a', 's', 34 ]
1.8 countOccurrences:检测数值出现次数
const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0);
countOccurrences([1, 1, 2, 1, 2, 3], 1); // 3
1.9 deepFlatten:递归扁平化数组
const deepFlatten = arr => [].concat(...arr.map(v => (Array.isArray(v) ? deepFlatten(v) : v)));
deepFlatten([1, [2], [[3], 4], 5]); // [1,2,3,4,5]
1.10 deepFlatten:递归扁平化数组
const deepFlatten = arr => [].concat(...arr.map(v => (Array.isArray(v) ? deepFlatten(v) : v)));
deepFlatten([1, [2], [[3], 4], 5]); // [1,2,3,4,5]
1.11 ArrayToObject:数组转对象
/**
* 数组转对象
* @param key
* @param arr
* @returns {*}
*/
const ArrayToObject = (key: string, arr: any) => {
if (arr instanceof Array) {
const ojb: { [key: string]: any } = {};
arr.forEach(
(a) => {
if (a && a[key]) ojb[a[key]] = a;
}
);
return ojb;
}
if (typeof arr === 'object') return arr;
return {};
};
const arr = ["Jack", "Bob", "Alice"]
ArrayToObject("0", arr) // {J: "Jack", B: "Bob", A: "Alice"}
1.12 ArrayIncludesArray: 判断数组1是否包含数组2
function includes(arr1, arr2) {
return arr2.every(val => arr1.includes(val));
}
let a = [1, 2, 3, 4, 5, 6, 7, 8];
let b = [1, 2];
let c = [3, 9];
console.log(includes(a, b)); //true
console.log(includes(a, c)); //false
1.13 middle: 求中位数
const middle = (arr) => {
let args=[...arr]; //收集参数转为数组
args.sort() //排序
if(args.length%2===0){ //判断数字个数是奇数还是偶数
return ((args[args.length/2]+args[args.length/2-1])/2);//偶数个取中间两个数的平均数
}else{
return args[parseInt(args.length/2)];//奇数个取最中间那个数
}
}
middle([1,2,3,4,5,6,7]) // 4
2. String
2.1 byteSize:返回字符串的字节长度
const byteSize = str => new Blob([str]).size;
byteSize('😀'); // 4
byteSize('Hello World'); // 11
2.2 capitalize:首字母大写
const capitalize = ([first, ...rest]) =>
first.toUpperCase() + rest.join('');
capitalize('fooBar'); // 'FooBar'
capitalize('fooBar', true); // 'Foobar'
2.3 capitalizeEveryWord:每个单词首字母大写
const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase());
capitalizeEveryWord('hello world!'); // 'Hello World!'
2.4 splitLines:将多行字符串拆分为行数组
const splitLines = str => str.split(/\r?\n/);
splitLines('This\nis a\nmultiline\nstring.\n'); // ['This', 'is a', 'multiline', 'string.' , '']
2.5 stripHTMLTags:删除字符串中的HTMl标签
const stripHTMLTags = str => str.replace(/<[^>]*>/g, '');
stripHTMLTags('<p><em>lorem</em> <strong>ipsum</strong></p>'); // 'lorem ipsum'
2.6 insertString :在字符串特定位置插入字符
const insertString = (source: string, start: number, newStr: string) => {
return source.slice(0, start) + newStr + source.slice(start);
};
insertString ('acd',1,'b'); // 'abcd'
2.7 getBirthById: 通过身份证获取出生日期
const getBirthById= (idCard) => {
var birthday = "";
if(idCard != null && idCard != ""){
if(idCard.length == 15){
birthday = "19" + idCard.slice(6,12);
} else if(idCard.length == 18){
birthday = idCard.slice(6,14);
}
birthday = birthday.replace(/(.{4})(.{2})/,"$1$2");
//通过正则表达式来指定输出格式为:1990-01-01
}
return birthday;
};
2.8 getSexById: 通过身份证获取性别
const GetSexById = (idCard) => {
var sexStr = '';
if (parseInt(idCard.slice(-2, -1)) % 2 == 1) {
sexStr = '1';
}
else {
sexStr = '2';
}
return sexStr;
};
2.9 getUUID: 生成UUID
export const getUUID = (format: string = null) => {
if (format === null) format = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
return format.replace(/[xy]/g, (c) => {
const r = Math.random() * 16 | 0;
const
v = c === "x" ? r : (r & 0x3 | 0x8);
const date = new Date().getTime();
const d = (v * date).toString(16);
return d.charAt(Math.random() * d.length | 0);
});
};
3. Number
3.1 randomIntegerInRange:生成指定范围的随机整数
const randomIntegerInRange = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
randomIntegerInRange(0, 5); // 3
3.2 round:四舍五入到指定位数
const round = (n, decimals = 0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`);
round(1.005, 2); // 1.01
3.3 sum:计算数组或多个数字的总和
const sum = (...arr) => [...arr].reduce((acc, val) => acc + val, 0);
sum(1, 2, 3, 4); // 10
sum(...[1, 2, 3, 4]); // 10
4. Object
4.1 forOwn:迭代属性并执行回调
const forOwn = (obj, fn) => Object.keys(obj).forEach(key => fn(obj[key], key, obj));
forOwn({ foo: 'bar', a: 1 }, v => console.log(v)); // 'bar', 1
4.2 is:检查值是否为特定类型。
const is = (type, val) => ![, null].includes(val) && val.constructor === type;
is(Array, [1]); // true
is(ArrayBuffer, new ArrayBuffer()); // true
is(Map, new Map()); // true
is(RegExp, /./g); // true
is(Set, new Set()); // true
is(WeakMap, new WeakMap()); // true
is(WeakSet, new WeakSet()); // true
is(String, ''); // true
is(String, new String('')); // true
is(Number, 1); // true
is(Number, new Number(1)); // true
is(Boolean, true); // true
is(Boolean, new Boolean(true)); // true
5. Function
5.1 attempt:捕获函数运行异常
const attempt = (fn, ...args) => {
try {
return fn(...args);
} catch (e) {
return e instanceof Error ? e : new Error(e);
}
};
var elements = attempt(function(selector) {
return document.querySelectorAll(selector);
}, '>_>');
if (elements instanceof Error) elements = []; // elements = []
5.2 defer:推迟执行
此代码段延迟了函数的执行,直到清除了当前调用堆栈。
const defer = (fn, ...args) => setTimeout(fn, 1, ...args);
defer(console.log, 'a'), console.log('b'); // logs 'b' then 'a'
5.3 runPromisesInSeries:运行多个Promises
const runPromisesInSeries = ps => ps.reduce((p, next) => p.then(next), Promise.resolve());
const delay = d => new Promise(r => setTimeout(r, d));
runPromisesInSeries([() => delay(1000), () => delay(2000)]);
//依次执行每个Promises ,总共需要3秒钟才能完成
5.4 timeTaken:计算函数执行时间
const timeTaken = callback => {
console.time('timeTaken');
const r = callback();
console.timeEnd('timeTaken');
return r;
};
timeTaken(() => Math.pow(2, 10)); // 1024, (logged): timeTaken: 0.02099609375ms
5.5 createEventHub:简单的发布/订阅模式
创建一个发布/订阅(发布-订阅)事件集线,有emit
,on
和off
方法。
- 使用
Object.create(null)
创建一个空的hub对象。 emit
,根据event参数解析处理程序数组,然后.forEach()
通过传入数据作为参数来运行每个处理程序。on
,为事件创建一个数组(若不存在则为空数组),然后.push()
将处理程序添加到该数组。off
,用.findIndex()
在事件数组中查找处理程序的索引,并使用.splice()
删除。
const createEventHub = () => ({
hub: Object.create(null),
emit(event, data) {
(this.hub[event] || []).forEach(handler => handler(data));
},
on(event, handler) {
if (!this.hub[event]) this.hub[event] = [];
this.hub[event].push(handler);
},
off(event, handler) {
const i = (this.hub[event] || []).findIndex(h => h === handler);
if (i > -1) this.hub[event].splice(i, 1);
if (this.hub[event].length === 0) delete this.hub[event];
}
});
用法:
const handler = data => console.log(data);
const hub = createEventHub();
let increment = 0;
// 订阅,监听不同事件
hub.on('message', handler);
hub.on('message', () => console.log('Message event fired'));
hub.on('increment', () => increment++);
// 发布:发出事件以调用所有订阅给它们的处理程序,并将数据作为参数传递给它们
hub.emit('message', 'hello world'); // 打印 'hello world' 和 'Message event fired'
hub.emit('message', { hello: 'world' }); // 打印 对象 和 'Message event fired'
hub.emit('increment'); // increment = 1
// 停止订阅
hub.off('message', handler);
6. Browser
6.1 isMobile: 判断设备是否是移动端
const isMobile = (userAgent: string) => {
const version = userAgent || navigator.userAgent;
return /phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone/i.test(version);
};
6.2 isMac: 判断系统是否是mac
const isMac = (userAgent: string) => {
const version = userAgent || navigator.userAgent;
return /macintosh|mac os x/i.test(version);
};
6.3 isWindows: 判断系统是否是mac
const isWindows = (userAgent: string) => {
const version = userAgent || navigator.userAgent;
if (version.indexOf("Windows") !== -1) {
return true;
}
};
6.4 whatOS: 判断当前的操作系统
const whatOS = (userAgent: string) => {
if (typeof userAgent !== "string") return "";
// 判断pc系统类型
if (userAgent.indexOf("Windows NT 5.1") !== -1) return "Windows Vista";
if (userAgent.indexOf("Windows NT 6.1") !== -1) return "Windows 7";
if (userAgent.indexOf("Windows NT 6.2") !== -1) return "Windows 8";
if (userAgent.indexOf("Windows NT 10") !== -1) return "Windows 10";
try {
return "MAC OSX " + userAgent.match(/.*?mac\sos\sx\s(.*?)([;)])/i)[1].replace(/_/g, ".");
} catch (e) {
// console.error(e);
}
try {
return "Android " + userAgent.match(/.*?Android\s(.*?);/i)[1];
} catch (e) {
}
if (userAgent.indexOf("Linux") !== -1) return "Linux";
// 判断手机系统类型
if (userAgent.indexOf("Windows Phone 8") !== -1) return "Windows Phone 8";
// PostMan测试
if (userAgent.indexOf("PostmanRuntime") !== -1) return "Postman";
try {
return "iPhone " + userAgent.match(/.*?\siPhone\sOS\s(.*?)\s/i)[1].replace(/_/g, ".");
} catch (e) {
}
return "other";
};
6.5 getBrowserClass: 获取浏览器类型
- ie:浏览器类型为IE/Edge
- firefox:浏览器类型为firefox
- chrome:浏览器类型为Opera/Safari/Chrome
/* 获取浏览器类型 */
export const getBrowserClass = () => {
const userAgent = navigator.userAgent; // 取得浏览器的userAgent字符串
const isOpera = userAgent.indexOf("Opera") > -1; // 判断是否Opera浏览器
// var isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1 && !isOpera; //判断是否IE浏览器
const isIE = window.ActiveXObject || "ActiveXObject" in window;
// var isEdge = userAgent.indexOf("Windows NT 6.1; Trident/7.0;") > -1 && !isIE; //判断是否IE的Edge浏览器
const isEdge = userAgent.indexOf("Edge") > -1; // 判断是否IE的Edge浏览器
const isFF = userAgent.indexOf("Firefox") > -1; // 判断是否Firefox浏览器
const isSafari = userAgent.indexOf("Safari") > -1 && userAgent.indexOf("Chrome") === -1; // 判断是否Safari浏览器
const isChrome = userAgent.indexOf("Chrome") > -1 && userAgent.indexOf("Safari") > -1 && !isEdge; // 判断Chrome浏览器
if (isIE) return "ie";
if (isFF) return "firefox";
if (isOpera) return "chrome";
if (isSafari) return "chrome";
if (isChrome) return "chrome";
if (isEdge) return "ie";
};
6.6 hide:隐藏所有的指定标签
const hide = (...el) => [...el].forEach(e => (e.style.display = 'none'));
hide(document.querySelectorAll('img')); // 隐藏所有<img>标签
6.7 CopyToClipboard: 复制到剪切板
export const CopyToClipboard = (str: string) => {
const el = document.createElement('textarea');
el.value = str;
el.setAttribute('readonly', '');
el.style.position = 'absolute';
el.style.left = '-9999px';
document.body.appendChild(el);
const selected =
document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false;
el.select();
document.execCommand('copy');
document.body.removeChild(el);
if (selected) {
document.getSelection().removeAllRanges();
document.getSelection().addRange(selected);
}
};
export const ParaCopy = (text: string) => {
const textareaEl = document.createElement("textarea");
textareaEl.setAttribute("readonly", "readonly"); // 防止手机上弹出软键盘
textareaEl.value = text;
document.body.appendChild(textareaEl);
textareaEl.select();
const res = document.execCommand("copy");
document.body.removeChild(textareaEl);
console.log("复制成功");
return res;
};
6.8 GetParamByName: 获取url参数
- name:参数的名称 key
- url:获取参数的url
/**
* 获取url参数
* @returns {string}
* @example
* getParamByName("a", "http://www.baidu.com?a=1&b=aaa") // "1"
* @example
* getParamByName("b", "http://www.baidu.com?a=1&b=aaa") // "aaa"
* @example
* getParamByName("c", "http://www.baidu.com?a=1&b=aaa") //""
*/
export const GetParamByName = (name: string, url = window.location.href) => {
name = name.replace(/[\[\]]/g, "\\$&");
const regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)");
const results = regex.exec(url);
if (!results) return "";
if (!results[2]) return "";
return decodeURIComponent(results[2].replace(/\+/g, " "));
};
6.9 currentURL:返回当前链接url
const currentURL = () => window.location.href;
currentURL(); // 'https://juejin.cn'
6.10 bottomVisible:检查页面底部是否可见
const bottomVisible = () =>
document.documentElement.clientHeight + window.scrollY >=
(document.documentElement.scrollHeight || document.documentElement.clientHeight);
bottomVisible(); // true
6.11 insertAfter:在指定元素之后插入新元素
const insertAfter = (el, htmlString) => el.insertAdjacentHTML('afterend', htmlString);
// <div id="myId">...</div> <p>after</p>
insertAfter(document.getElementById('myId'), '<p>after</p>');
6.12 insertBefore:在指定元素之前插入新元素
const insertBefore = (el, htmlString) => el.insertAdjacentHTML('beforebegin', htmlString);
insertBefore(document.getElementById('myId'), '<p>before</p>'); // <p>before</p> <div id="myId">...</div>
6.13 nodeListToArray:转换nodeList为数组
const nodeListToArray = nodeList => [...nodeList];
nodeListToArray(document.childNodes); // [ <!DOCTYPE html>, html ]
6.14 randomHexColorCode:随机十六进制颜色
const randomHexColorCode = () => {
let n = (Math.random() * 0xfffff * 1000000).toString(16);
return '#' + n.slice(0, 6);
};
randomHexColorCode(); // "#e34155"
6.15 ScrollToTop: 滚动到顶部
export const ScrollToTop = () => {
const c = document.documentElement.scrollTop || document.body.scrollTop;
if (c > 0) {
window.requestAnimationFrame(ScrollToTop);
window.scrollTo(0, c - c / 8);
}
};
6.9 smoothScroll:滚动到指定元素区域
使用dom的scrollIntoView
方法
const smoothScroll = element =>
document.querySelector(element).scrollIntoView({
behavior: 'smooth'
});
smoothScroll('#fooBar');
smoothScroll('.fooBar');