JS 开发常用工具函数

论坛 期权论坛 期权     
前端开发   2019-7-27 22:21   3679   0
作者:hfhan
链接:https://segmentfault.com/a/1190000019601333
1、isStatic:检测数据是不是除了symbol外的原始数据
  1. function isStatic(value) {
  2.     return(
  3.         typeof value === 'string' ||
  4.         typeof value === 'number' ||
  5.         typeof value === 'boolean' ||
  6.         typeof value === 'undefined' ||
  7.         value === null
  8.     )
  9. }
复制代码

[h1]2、isPrimitive:检测数据是不是原始数据[/h1]
  1. function isPrimitive(value) {
  2.     return isStatic(value) || typeof value === 'symbol'
  3. }
复制代码

[h1]3、isObject:判断数据是不是引用类型的数据 (例如: arrays, functions, objects, regexes, new Number(0),以及 new String(''))[/h1]
  1. function isObject(value) {
  2.       let type = typeof value;
  3.       return value != null && (type == 'object' || type == 'function');
  4. }
复制代码

[h1]4、isObjectLike:检查 value 是否是 类对象。 如果一个值是类对象,那么它不应该是 null,而且 typeof 后的结果是 "object"[/h1]
  1. function isObjectLike(value) {
  2.       return value != null && typeof value == 'object';
  3. }
复制代码

[h1]5、getRawType:获取数据类型,返回结果为 Number、String、Object、Array等[/h1]
  1. function getRawType(value) {
  2.     return Object.prototype.toString.call(value).slice(8, -1)
  3. }
  4. //getoRawType([]) ==> Array
复制代码

[h1]6、isPlainObject:判断数据是不是Object类型的数据[/h1]
  1. function isPlainObject(obj) {
  2.     return Object.prototype.toString.call(obj) === '[object Object]'
  3. }
复制代码

[h1]7、isArray:判断数据是不是数组类型的数据[/h1]
  1. function isArray(arr) {
  2.     return Object.prototype.toString.call(arr) === '[object Array]'
  3. }
复制代码
将isArray挂载到Array上
  1. Array.isArray = Array.isArray || isArray;
复制代码

[h1]8、isRegExp:判断数据是不是正则对象[/h1]
  1. function isRegExp(value) {
  2.     return Object.prototype.toString.call(value) === '[object RegExp]'
  3. }
复制代码

[h1]9、isDate:判断数据是不是时间对象[/h1]
  1. function isDate(value) {
  2.     return Object.prototype.toString.call(value) === '[object Date]'
  3. }
复制代码

[h1]10、isNative:判断 value 是不是浏览器内置函数[/h1]
内置函数toString后的主体代码块为 [native code] ,而非内置函数则为相关代码,所以非内置函数可以进行拷贝(toString后掐头去尾再由Function转)
  1. function isNative(value) {
  2.     return typeof value === 'function' && /native code/.test(value.toString())
  3. }
复制代码

[h1]11、isFunction:检查 value 是不是函数[/h1]
  1. function isFunction(value) {
  2.     return Object.prototype.toString.call(value) === '[object Function]'
  3. }
复制代码

[h1]12、isLength:检查 value 是否为有效的类数组长度[/h1]
  1. function isLength(value) {
  2.       return typeof value == 'number' && value > -1 && value % 1 == 0 && value  abCdEf
  3. //使用记忆函数
  4. let _camelize = cached(camelize)
复制代码

[h1]17、hyphenate:驼峰命名转横线命名:拆分字符串,使用 - 相连,并且转换为小写[/h1]
  1. let hyphenateRE = /\B([A-Z])/g;
  2. function hyphenate(str){
  3.     return str.replace(hyphenateRE, '-$1').toLowerCase()
  4. }
  5. //abCd ==> ab-cd
  6. //使用记忆函数
  7. let _hyphenate = cached(hyphenate);
复制代码

[h1]18、capitalize:字符串首位大写[/h1]
  1. function capitalize(str){
  2.     return str.charAt(0).toUpperCase() + str.slice(1)
  3. }
  4. // abc ==> Abc
  5. //使用记忆函数
  6. let _capitalize = cached(capitalize)
复制代码

[h1]19、extend:将属性混合到目标对象中[/h1]
  1. function extend(to, _from) {
  2.     for(let key in _from) {
  3.         to[key] = _from[key];
  4.     }
  5.     return to
  6. }
复制代码

[h1]20、Object.assign:对象属性复制,浅拷贝[/h1]
  1. Object.assign = Object.assign || function(){
  2.     if(arguments.length == 0) throw new TypeError('Cannot convert undefined or null to object');
  3.     let target = arguments[0],
  4.         args = Array.prototype.slice.call(arguments, 1),
  5.         key
  6.     args.forEach(function(item){
  7.         for(key in item){
  8.             item.hasOwnProperty(key) && ( target[key] = item[key] )
  9.         }
  10.     })
  11.     return target
  12. }
复制代码
使用Object.assign可以浅克隆一个对象:
  1. let clone = Object.assign({}, target)
复制代码
简单的深克隆可以使用JSON.parse()和JSON.stringify(),这两个api是解析json数据的,所以只能解析除symbol外的原始类型及数组和对象
  1. let clone = JSON.parse( JSON.stringify(target) )
复制代码

[h1]21、clone:克隆数据,可深度克隆[/h1]
这里列出了原始类型,时间、正则、错误、数组、对象的克隆规则,其他的可自行补充
  1. function clone(value, deep){
  2.     if(isPrimitive(value)){
  3.         return value
  4.     }
  5.     if (isArrayLike(value)) { //是类数组
  6.         value = Array.prototype.slice.call(value)
  7.         return value.map(item => deep ? clone(item, deep) : item)
  8.        }else if(isPlainObject(value)){ //是对象
  9.            let target = {}, key;
  10.           for (key in value) {
  11.             value.hasOwnProperty(key) && ( target[key] = deep ? clone(value[key], deep) : value[key] )
  12.         }
  13.     }
  14.     let type = getRawType(value)
  15.     switch(type){
  16.         case 'Date':
  17.         case 'RegExp':
  18.         case 'Error': value = new window[type](value); break;
  19.     }
  20.     return value
  21. }
复制代码
[h1][/h1][h1]22、识别各种浏览器及平台[/h1]
  1. //运行环境是浏览器
  2. let inBrowser = typeof window !== 'undefined';
  3. //运行环境是微信
  4. let inWeex = typeof WXEnvironment !== 'undefined' && !!WXEnvironment.platform;
  5. let weexPlatform = inWeex && WXEnvironment.platform.toLowerCase();
  6. //浏览器 UA 判断
  7. let UA = inBrowser && window.navigator.userAgent.toLowerCase();
  8. let isIE = UA && /msie|trident/.test(UA);
  9. let isIE9 = UA && UA.indexOf('msie 9.0') > 0;
  10. let isEdge = UA && UA.indexOf('edge/') > 0;
  11. let isAndroid = (UA && UA.indexOf('android') > 0) || (weexPlatform === 'android');
  12. let isIOS = (UA && /iphone|ipad|ipod|ios/.test(UA)) || (weexPlatform === 'ios');
  13. let isChrome = UA && /chrome\/\d+/.test(UA) && !isEdge;
复制代码
[h1][/h1][h1]23、getExplorerInfo:获取浏览器信息[/h1]
  1. function getExplorerInfo() {
  2.     let t = navigator.userAgent.toLowerCase();
  3.     return 0 = 1;
  4.     }
  5.     return res
  6. };
  7. //repeat('123',3) ==> 123123123
复制代码
[h1][/h1][h1]28、dateFormater:格式化时间[/h1]
  1. function dateFormater(formater, t){
  2.     let date = t ? new Date(t) : new Date(),
  3.         Y = date.getFullYear() + '',
  4.         M = date.getMonth() + 1,
  5.         D = date.getDate(),
  6.         H = date.getHours(),
  7.         m = date.getMinutes(),
  8.         s = date.getSeconds();
  9.     return formater.replace(/YYYY|yyyy/g,Y)
  10.         .replace(/YY|yy/g,Y.substr(2,2))
  11.         .replace(/MM/g,(M 2019年06月26日
  12. // dateStrForma('2019年06月26日', 'YYYY年MM月DD日', 'YYYYMMDD') ==> 20190626
  13. // 一般的也可以使用正则来实现
  14. //'2019年06月26日'.replace(/(\d{4})年(\d{2})月(\d{2})日/, '$1-$2-$3') ==> 2019-06-26
复制代码
[h1][/h1][h1]30、getPropByPath:根据字符串路径获取对象属性 : 'obj[0].count'[/h1]
  1. function getPropByPath(obj, path, strict) {
  2.       let tempObj = obj;
  3.       path = path.replace(/\[(\w+)\]/g, '.$1'); //将[0]转化为.0
  4.       path = path.replace(/^\./, ''); //去除开头的.
  5.       let keyArr = path.split('.'); //根据.切割
  6.       let i = 0;
  7.       for (let len = keyArr.length; i < len - 1; ++i) {
  8.         if (!tempObj && !strict) break;
  9.         let key = keyArr[i];
  10.         if (key in tempObj) {
  11.             tempObj = tempObj[key];
  12.         } else {
  13.             if (strict) {//开启严格模式,没找到对应key值,抛出错误
  14.                 throw new Error('please transfer a valid prop path to form item!');
  15.             }
  16.             break;
  17.         }
  18.       }
  19.       return {
  20.         o: tempObj, //原始数据
  21.         k: keyArr[i], //key值
  22.         v: tempObj ? tempObj[keyArr[i]] : null // key值对应的值
  23.       };
  24. };
复制代码
[h1][/h1][h1]31、GetUrlParam:获取Url参数,返回一个对象[/h1]
  1. function GetUrlParam(){
  2.     let url = document.location.toString();
  3.     let arrObj = url.split("?");
  4.     let params = Object.create(null)
  5.     if (arrObj.length > 1){
  6.         arrObj = arrObj[1].split("&");
  7.         arrObj.forEach(item=>{
  8.             item = item.split("=");
  9.             params[item[0]] = item[1]
  10.         })
  11.     }
  12.     return params;
  13. }
  14. // ?a=1&b=2&c=3 ==> {a: "1", b: "2", c: "3"}
复制代码
[h1][/h1][h1]32、downloadFile:base64数据导出文件,文件下载[/h1]
  1. function downloadFile(filename, data){
  2.     let DownloadLink = document.createElement('a');
  3.     if ( DownloadLink ){
  4.         document.body.appendChild(DownloadLink);
  5.         DownloadLink.style = 'display: none';
  6.         DownloadLink.download = filename;
  7.         DownloadLink.href = data;
  8.         if ( document.createEvent ){
  9.             let DownloadEvt = document.createEvent('MouseEvents');
  10.             DownloadEvt.initEvent('click', true, false);
  11.             DownloadLink.dispatchEvent(DownloadEvt);
  12.         }
  13.         else if ( document.createEventObject )
  14.             DownloadLink.fireEvent('onclick');
  15.         else if (typeof DownloadLink.onclick == 'function' )
  16.             DownloadLink.onclick();
  17.         document.body.removeChild(DownloadLink);
  18.     }
  19. }
复制代码

[h1]33、toFullScreen:全屏[/h1]
  1. function toFullScreen(){
  2.     let elem = document.body;
  3.     elem.webkitRequestFullScreen
  4.     ? elem.webkitRequestFullScreen()
  5.     : elem.mozRequestFullScreen
  6.     ? elem.mozRequestFullScreen()
  7.     : elem.msRequestFullscreen
  8.     ? elem.msRequestFullscreen()
  9.     : elem.requestFullScreen
  10.     ? elem.requestFullScreen()
  11.     : alert("浏览器不支持全屏");
  12. }
复制代码

[h1]34、exitFullscreen:退出全屏[/h1]
  1. function exitFullscreen(){
  2.     let elem = parent.document;
  3.     elem.webkitCancelFullScreen
  4.     ? elem.webkitCancelFullScreen()
  5.     : elem.mozCancelFullScreen
  6.     ? elem.mozCancelFullScreen()
  7.     : elem.cancelFullScreen
  8.     ? elem.cancelFullScreen()
  9.     : elem.msExitFullscreen
  10.     ? elem.msExitFullscreen()
  11.     : elem.exitFullscreen
  12.     ? elem.exitFullscreen()
  13.     : alert("切换失败,可尝试Esc退出");
  14. }
复制代码

[h1]35、requestAnimationFrame:window动画[/h1]
  1. window.requestAnimationFrame = window.requestAnimationFrame ||
  2.     window.webkitRequestAnimationFrame ||
  3.     window.mozRequestAnimationFrame ||
  4.     window.msRequestAnimationFrame ||
  5.     window.oRequestAnimationFrame ||
  6.     function (callback) {
  7.         //为了使setTimteout的尽可能的接近每秒60帧的效果
  8.         window.setTimeout(callback, 1000 / 60);
  9.     };
  10. window.cancelAnimationFrame = window.cancelAnimationFrame ||
  11.     Window.webkitCancelAnimationFrame ||
  12.     window.mozCancelAnimationFrame ||
  13.     window.msCancelAnimationFrame ||
  14.     window.oCancelAnimationFrame ||
  15.     function (id) {
  16.         //为了使setTimteout的尽可能的接近每秒60帧的效果
  17.         window.clearTimeout(id);
  18.     }
复制代码
[h1][/h1][h1]36、_isNaN:检查数据是否是非数字值[/h1]
原生的isNaN会把参数转换成数字(valueof),而null、true、false以及长度小于等于1的数组(元素为非NaN数据)会被转换成数字,这不是我想要的。Symbol类型的数据不具有valueof接口,所以isNaN会抛出错误,这里放在后面,可避免错误
  1. function _isNaN(v){
  2.     return !(typeof v === 'string' || typeof v === 'number') || isNaN(v)
  3. }
复制代码

[h1]37、max:求取数组中非NaN数据中的最大值[/h1]
  1. function max(arr){
  2.     arr = arr.filter(item => !_isNaN(item))
  3.     return arr.length ? Math.max.apply(null, arr) : undefined
  4. }
  5. //max([1, 2, '11', null, 'fdf', []]) ==> 11
复制代码
[h1][/h1][h1]38、min:求取数组中非NaN数据中的最小值[/h1]
  1. function min(arr){
  2.     arr = arr.filter(item => !_isNaN(item))
  3.     return arr.length ? Math.min.apply(null, arr) : undefined
  4. }
  5. //min([1, 2, '11', null, 'fdf', []]) ==> 1
复制代码
[h1][/h1][h1]39、random:返回一个lower - upper之间的随机数[/h1]
lower、upper无论正负与大小,但必须是非NaN的数据
  1. function random(lower, upper){
  2.     lower = +lower || 0
  3.     upper = +upper || 0
  4.     return Math.random() * (upper - lower) + lower;
  5. }
  6. //random(0, 0.5) ==> 0.3567039135734613
  7. //random(2, 1) ===> 1.6718418553475423
  8. //random(-2, -1) ==> -1.4474325452361945
复制代码
[h1][/h1][h1][/h1][h1]40、Object.keys:返回一个由一个给定对象的自身可枚举属性组成的数组[/h1]
  1. Object.keys = Object.keys || function keys(object) {
  2.     if(object === null || object === undefined){
  3.         throw new TypeError('Cannot convert undefined or null to object');
  4.     }
  5.     let result = []
  6.     if(isArrayLike(object) || isPlainObject(object)){
  7.         for (let key in object) {
  8.             object.hasOwnProperty(key) && ( result.push(key) )
  9.         }
  10.     }
  11.     return result
  12. }
复制代码
[h1][/h1][h1]41、Object.values:返回一个给定对象自身的所有可枚举属性值的数组[/h1]
  1. Object.values = Object.values || function values(object) {
  2.     if(object === null || object === undefined){
  3.         throw new TypeError('Cannot convert undefined or null to object');
  4.     }
  5.     let result = []
  6.     if(isArrayLike(object) || isPlainObject(object)){
  7.         for (let key in object) {
  8.             object.hasOwnProperty(key) && ( result.push(object[key]) )
  9.         }
  10.     }
  11.     return result
  12. }
复制代码
[h1][/h1][h1]42、arr.fill:使用 value 值来填充 array,从start位置开始, 到end位置结束(但不包含end位置),返回原数组[/h1]
  1. Array.prototype.fill = Array.prototype.fill || function fill(value, start, end) {
  2.     let ctx = this
  3.     let length = ctx.length;
  4.     start = parseInt(start)
  5.     if(isNaN(start)){
  6.         start = 0
  7.     }else if (start < 0) {
  8.         start = -start > length ? 0 : (length + start);
  9.       }
  10.       end = parseInt(end)
  11.       if(isNaN(end) || end > length){
  12.           end = length
  13.       }else if (end < 0) {
  14.         end += length;
  15.     }
  16.     while (start < end) {
  17.         ctx[start++] = value;
  18.     }
  19.     return ctx;
  20. }
  21. //Array(3).fill(2) ===> [2, 2, 2]
复制代码

[h1]43、arr.includes:用来判断一个数组是否包含一个指定的值,如果是返回 true,否则false,可指定开始查询的位置[/h1]
  1. Array.prototype.includes = Array.prototype.includes || function includes(value, start){
  2.     let ctx = this
  3.     let length = ctx.length;
  4.     start = parseInt(start)
  5.     if(isNaN(start)){
  6.         start = 0
  7.     }else if (start < 0) {
  8.         start = -start > length ? 0 : (length + start);
  9.       }
  10.     let index = ctx.indexOf(value)
  11.     return index >= start;
  12. }
复制代码
[h1][/h1][h1]44、arr.find:返回数组中通过测试(函数fn内判断)的第一个元素的值[/h1]
  1. Array.prototype.find = Array.prototype.find || function find(fn, ctx){
  2.     fn = fn.bind(ctx)
  3.     let result;
  4.     this.some((value, index, arr), thisValue) => {
  5.         return fn(value, index, arr) ? (result = value, true) : false
  6.     })
  7.     return result
  8. }
复制代码
[h1][/h1][h1]45、arr.findIndex :返回数组中通过测试(函数fn内判断)的第一个元素的下标[/h1]
  1. Array.prototype.findIndex = Array.prototype.findIndex || function findIndex(fn, ctx){
  2.     fn = fn.bind(ctx)
  3.     let result;
  4.     this.some((value, index, arr), thisValue) => {
  5.         return fn(value, index, arr) ? (result = index, true) : false
  6.     })
  7.     return result
  8. }
复制代码
[h1][/h1][h1]46、performance.timing:利用performance.timing进行性能分析[/h1]
  1. window.onload = function(){
  2.     setTimeout(function(){
  3.         let t = performance.timing
  4.         console.log('DNS查询耗时 :' + (t.domainLookupEnd - t.domainLookupStart).toFixed(0))
  5.         console.log('TCP链接耗时 :' + (t.connectEnd - t.connectStart).toFixed(0))
  6.         console.log('request请求耗时 :' + (t.responseEnd - t.responseStart).toFixed(0))
  7.         console.log('解析dom树耗时 :' + (t.domComplete - t.domInteractive).toFixed(0))
  8.         console.log('白屏时间 :' + (t.responseStart - t.navigationStart).toFixed(0))
  9.         console.log('domready时间 :' + (t.domContentLoadedEventEnd - t.navigationStart).toFixed(0))
  10.         console.log('onload时间 :' + (t.loadEventEnd - t.navigationStart).toFixed(0))
  11.         if(t = performance.memory){
  12.             console.log('js内存使用占比 :' + (t.usedJSHeapSize / t.totalJSHeapSize * 100).toFixed(2) + '%')
  13.         }
  14.     })
  15. }
复制代码
[h1]47、禁止某些键盘事件:[/h1]
  1. document.addEventListener('keydown', function(event){
  2.     return !(
  3.         112 == event.keyCode || //F1
  4.         123 == event.keyCode || //F12
  5.         event.ctrlKey && 82 == event.keyCode || //ctrl + R
  6.         event.ctrlKey && 78 == event.keyCode || //ctrl + N
  7.         event.shiftKey && 121 == event.keyCode || //shift + F10
  8.         event.altKey && 115 == event.keyCode || //alt + F4
  9.         "A" == event.srcElement.tagName && event.shiftKey //shift + 点击a标签
  10.     ) || (event.returnValue = false)
  11. });
复制代码

[h1]48、禁止右键、选择、复制[/h1]
  1. ['contextmenu', 'selectstart', 'copy'].forEach(function(ev){
  2.     document.addEventListener(ev, function(event){
  3.         return event.returnValue = false
  4.     })
  5. });
复制代码
github地址:https://github.com/hfhan/tools
●编号989,输入编号直达本文

●输入m获取文章目录
推荐↓↓↓
Web开发
更多推荐《25个技术类微信公众号
涵盖:程序人生、算法与数据结构、黑客技术与网络安全、大数据技术、前端开发、Java、Python、Web开发、安卓开发、iOS开发、C/C++、.NET、Linux、数据库、运维等。
分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:55
帖子:11
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP