[/url]
[url=https://mp.weixin.qq.com/s?__biz=Mzg5MzAyNDI4Mw==&mid=2247484104&idx=4&sn=d09c891f3f839397b0a34beff918527d&chksm=c03463bcf743eaaa6616768662262c1d61c04c013e2c251d0b8410b2fa5291183e3ac5520767&token=127291324&lang=zh_CN&scene=21#wechat_redirect]黑客技术点击右侧关注,了解黑客的世界!
Java开发进阶点击右侧关注,掌握进阶之路!
Linux编程点击右侧关注,免费入门到精通!
[h1]作者丨hfhan[/h1]https://segmentfault.com/a/1190000019601333
[h1][/h1][h1]1、isStatic:检测数据是不是除了symbol外的原始数据[/h1]
function isStatic(value) { return( typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' || typeof value === 'undefined' || value === null )}
[h1]2、isPrimitive:检测数据是不是原始数据[/h1]
function isPrimitive(value) { return isStatic(value) || typeof value === 'symbol'}
[h1]3、isObject:判断数据是不是引用类型的数据 (例如:arrays, functions, objects, regexes, new Number(0),以及 new String(''))[/h1]
function isObject(value) { let type = typeof value; return value != null && (type == 'object' || type == 'function');}
[h1]4、isObjectLike:检查 value 是否是 类对象。如果一个值是类对象,那么它不应该是 null,而且 typeof 后的结果是 "object"[/h1]
function isObjectLike(value) { return value != null && typeof value == 'object';}
[h1]5、getRawType:获取数据类型,返回结果为 Number、String、Object、Array等[/h1]
function getRawType(value) { return Object.prototype.toString.call(value).slice(8, -1)}//getoRawType([]) ==> Array
[h1]6、isPlainObject:判断数据是不是Object类型的数据[/h1]
function isPlainObject(obj) { return Object.prototype.toString.call(obj) === '[object Object]'}
[h1]7、isArray:判断数据是不是数组类型的数据[/h1]
function isArray(arr) { return Object.prototype.toString.call(arr) === '[object Array]'}
将isArray挂载到Array上
Array.isArray = Array.isArray || isArray;
8、isRegExp:判断数据是不是正则对象
function isRegExp(value) { return Object.prototype.toString.call(value) === '[object RegExp]'}
[h1]9、isDate:判断数据是不是时间对象[/h1]
function isDate(value) { return Object.prototype.toString.call(value) === '[object Date]'}
[h1]10、isNative:判断 value 是不是浏览器内置函数[/h1]
内置函数toString后的主体代码块为 [native code] ,而非内置函数则为相关代码,所以非内置函数可以进行拷贝(toString后掐头去尾再由Function转)
function isNative(value) { return typeof value === 'function' && /native code/.test(value.toString())}
[h1]11、isFunction:检查 value 是不是函数[/h1]
function isFunction(value) { return Object.prototype.toString.call(value) === '[object Function]'}
[h1]12、isLength:检查 value 是否为有效的类数组长度[/h1]
function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value abCdEf//使用记忆函数let _camelize = cached(camelize)
17、hyphenate:驼峰命名转横线命名:拆分字符串,使用 - 相连,并且转换为小写
let hyphenateRE = /\B([A-Z])/g;function hyphenate(str){ return str.replace(hyphenateRE, '-$1').toLowerCase()}//abCd ==> ab-cd//使用记忆函数let _hyphenate = cached(hyphenate);
[h1]18、capitalize:字符串首位大写[/h1]
function capitalize(str){ return str.charAt(0).toUpperCase() + str.slice(1)}// abc ==> Abc//使用记忆函数let _capitalize = cached(capitalize)
[h1][/h1][h1]19、extend:将属性混合到目标对象中[/h1]
function extend(to, _from) { for(let key in _from) { to[key] = _from[key]; } return to}
[h1]20、Object.assign:对象属性复制,浅拷贝[/h1]
Object.assign = Object.assign || function(){ if(arguments.length == 0) throw new TypeError('Cannot convert undefined or null to object'); let target = arguments[0], args = Array.prototype.slice.call(arguments, 1), key args.forEach(function(item){ for(key in item){ item.hasOwnProperty(key) && ( target[key] = item[key] ) } }) return target}
使用Object.assign可以浅克隆一个对象:
let clone = Object.assign({}, target)
简单的深克隆可以使用JSON.parse()和JSON.stringify(),这两个api是解析json数据的,所以只能解析除symbol外的原始类型及数组和对象
let clone = JSON.parse( JSON.stringify(target) )
[h1]21、clone:克隆数据,可深度克隆[/h1]
这里列出了原始类型,时间、正则、错误、数组、对象的克隆规则,其他的可自行补充
function clone(value, deep){ if(isPrimitive(value)){ return value } if (isArrayLike(value)) { //是类数组 value = Array.prototype.slice.call(value) return value.map(item => deep ? clone(item, deep) : item) }else if(isPlainObject(value)){ //是对象 let target = {}, key; for (key in value) { value.hasOwnProperty(key) && ( target[key] = deep ? clone(value[key], deep) : value[key] ) } } let type = getRawType(value) switch(type){ case 'Date': case 'RegExp': case 'Error': value = new window[type](value); break; } return value}
[h1]22、识别各种浏览器及平台[/h1][h1][/h1]//运行环境是浏览器let inBrowser = typeof window !== 'undefined';//运行环境是微信let inWeex = typeof WXEnvironment !== 'undefined' && !!WXEnvironment.platform;let weexPlatform = inWeex && WXEnvironment.platform.toLowerCase();//浏览器 UA 判断let UA = inBrowser && window.navigator.userAgent.toLowerCase();let isIE = UA && /msie|trident/.test(UA);let isIE9 = UA && UA.indexOf('msie 9.0') > 0;let isEdge = UA && UA.indexOf('edge/') > 0;let isAndroid = (UA && UA.indexOf('android') > 0) || (weexPlatform === 'android');let isIOS = (UA && /iphone|ipad|ipod|ios/.test(UA)) || (weexPlatform === 'ios');let isChrome = UA && /chrome\/\d+/.test(UA) && !isEdge;
[h1][/h1][h1]23、getExplorerInfo:获取浏览器信息[/h1][h1][/h1]function getExplorerInfo() { let t = navigator.userAgent.toLowerCase(); return 0 = 1; } return res};//repeat('123',3) ==> 123123123
[h1][/h1][h1]28、dateFormater:格式化时间[/h1][h1][/h1]function dateFormater(formater, t){ let date = t ? new Date(t) : new Date(), Y = date.getFullYear() + '', M = date.getMonth() + 1, D = date.getDate(), H = date.getHours(), m = date.getMinutes(), s = date.getSeconds(); return formater.replace(/YYYY|yyyy/g,Y) .replace(/YY|yy/g,Y.substr(2,2)) .replace(/MM/g,(M 2019年06月26日// dateStrForma('2019年06月26日', 'YYYY年MM月DD日', 'YYYYMMDD') ==> 20190626// 一般的也可以使用正则来实现//'2019年06月26日'.replace(/(\d{4})年(\d{2})月(\d{2})日/, '$1-$2-$3') ==> 2019-06-26
[h1]30、getPropByPath:根据字符串路径获取对象属性 : 'obj[0].count'[/h1]
function getPropByPath(obj, path, strict) { let tempObj = obj; path = path.replace(/\[(\w+)\]/g, '.$1'); //将[0]转化为.0 path = path.replace(/^\./, ''); //去除开头的. let keyArr = path.split('.'); //根据.切割 let i = 0; for (let len = keyArr.length; i < len - 1; ++i) { if (!tempObj && !strict) break; let key = keyArr; if (key in tempObj) { tempObj = tempObj[key]; } else { if (strict) {//开启严格模式,没找到对应key值,抛出错误 throw new Error('please transfer a valid prop path to form item!'); } break; } } return { o: tempObj, //原始数据 k: keyArr, //key值 v: tempObj ? tempObj[keyArr] : null // key值对应的值 };};
[h1]31、GetUrlParam:获取Url参数,返回一个对象[/h1]
function GetUrlParam(){ let url = document.location.toString(); let arrObj = url.split("?"); let params = Object.create(null) if (arrObj.length > 1){ arrObj = arrObj[1].split("&"); arrObj.forEach(item=>{ item = item.split("="); params[item[0]] = item[1] }) } return params;}// ?a=1&b=2&c=3 ==> {a: "1", b: "2", c: "3"}
[h1]32、downloadFile:base64数据导出文件,文件下载[/h1][h1][/h1]function downloadFile(filename, data){ let DownloadLink = document.createElement('a'); if ( DownloadLink ){ document.body.appendChild(DownloadLink); DownloadLink.style = 'display: none'; DownloadLink.download = filename; DownloadLink.href = data; if ( document.createEvent ){ let DownloadEvt = document.createEvent('MouseEvents'); DownloadEvt.initEvent('click', true, false); DownloadLink.dispatchEvent(DownloadEvt); } else if ( document.createEventObject ) DownloadLink.fireEvent('onclick'); else if (typeof DownloadLink.onclick == 'function' ) DownloadLink.onclick(); document.body.removeChild(DownloadLink); }}
[h1][/h1][h1]33、toFullScreen:全屏[/h1]
function toFullScreen(){ let elem = document.body; elem.webkitRequestFullScreen ? elem.webkitRequestFullScreen() : elem.mozRequestFullScreen ? elem.mozRequestFullScreen() : elem.msRequestFullscreen ? elem.msRequestFullscreen() : elem.requestFullScreen ? elem.requestFullScreen() : alert("浏览器不支持全屏");}
[h1]34、exitFullscreen:退出全屏[/h1][h1][/h1]function exitFullscreen(){ let elem = parent.document; elem.webkitCancelFullScreen ? elem.webkitCancelFullScreen() : elem.mozCancelFullScreen ? elem.mozCancelFullScreen() : elem.cancelFullScreen ? elem.cancelFullScreen() : elem.msExitFullscreen ? elem.msExitFullscreen() : elem.exitFullscreen ? elem.exitFullscreen() : alert("切换失败,可尝试Esc退出");}
[h1][/h1][h1]35、requestAnimationFrame:window动画[/h1][h1][/h1]window.requestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.msRequestAnimationFrame || window.oRequestAnimationFrame || function (callback) { //为了使setTimteout的尽可能的接近每秒60帧的效果 window.setTimeout(callback, 1000 / 60); };window.cancelAnimationFrame = window.cancelAnimationFrame || Window.webkitCancelAnimationFrame || window.mozCancelAnimationFrame || window.msCancelAnimationFrame || window.oCancelAnimationFrame || function (id) { //为了使setTimteout的尽可能的接近每秒60帧的效果 window.clearTimeout(id); }
[h1][/h1][h1]36、_isNaN:检查数据是否是非数字值[/h1]
原生的isNaN会把参数转换成数字(valueof),而null、true、false以及长度小于等于1的数组(元素为非NaN数据)会被转换成数字,这不是我想要的。Symbol类型的数据不具有valueof接口,所以isNaN会抛出错误,这里放在后面,可避免错误
function _isNaN(v){ return !(typeof v === 'string' || typeof v === 'number') || isNaN(v)}37、max:求取数组中非NaN数据中的最大值function max(arr){ arr = arr.filter(item => !_isNaN(item)) return arr.length ? Math.max.apply(null, arr) : undefined}//max([1, 2, '11', null, 'fdf', []]) ==> 11
[h1]38、min:求取数组中非NaN数据中的最小值[/h1]
function min(arr){ arr = arr.filter(item => !_isNaN(item)) return arr.length ? Math.min.apply(null, arr) : undefined}//min([1, 2, '11', null, 'fdf', []]) ==> 1
[h1]39、random:返回一个lower - upper之间的随机数[/h1]
lower、upper无论正负与大小,但必须是非NaN的数据
function random(lower, upper){ lower = +lower || 0 upper = +upper || 0 return Math.random() * (upper - lower) + lower;}//random(0, 0.5) ==> 0.3567039135734613//random(2, 1) ===> 1.6718418553475423//random(-2, -1) ==> -1.4474325452361945
[h1]40、Object.keys:返回一个由一个给定对象的自身可枚举属性组成的数组[/h1]
Object.keys = Object.keys || function keys(object) { if(object === null || object === undefined){ throw new TypeError('Cannot convert undefined or null to object'); } let result = [] if(isArrayLike(object) || isPlainObject(object)){ for (let key in object) { object.hasOwnProperty(key) && ( result.push(key) ) } } return result}
[h1]41、Object.values:返回一个给定对象自身的所有可枚举属性值的数组[/h1]
Object.values = Object.values || function values(object) { if(object === null || object === undefined){ throw new TypeError('Cannot convert undefined or null to object'); } let result = [] if(isArrayLike(object) || isPlainObject(object)){ for (let key in object) { object.hasOwnProperty(key) && ( result.push(object[key]) ) } } return result}
[h1]42、arr.fill:使用 value 值来填充 array,从start位置开始, 到end位置结束(但不包含end位置),返回原数组[/h1]
Array.prototype.fill = Array.prototype.fill || function fill(value, start, end) { let ctx = this let length = ctx.length; start = parseInt(start) if(isNaN(start)){ start = 0 }else if (start < 0) { start = -start > length ? 0 : (length + start); } end = parseInt(end) if(isNaN(end) || end > length){ end = length }else if (end < 0) { end += length; } while (start < end) { ctx[start++] = value; } return ctx;}//Array(3).fill(2) ===> [2, 2, 2]
[h1]43、arr.includes:用来判断一个数组是否包含一个指定的值,如果是返回 true,否则false,可指定开始查询的位置[/h1]
Array.prototype.includes = Array.prototype.includes || function includes(value, start){ let ctx = this let length = ctx.length; start = parseInt(start) if(isNaN(start)){ start = 0 }else if (start < 0) { start = -start > length ? 0 : (length + start); } let index = ctx.indexOf(value) return index >= start;}
[h1]44、arr.find:返回数组中通过测试(函数fn内判断)的第一个元素的值[/h1]
Array.prototype.find = Array.prototype.find || function find(fn, ctx){ fn = fn.bind(ctx) let result; this.some((value, index, arr), thisValue) => { return fn(value, index, arr) ? (result = value, true) : false }) return result}
[h1]45、arr.findIndex :返回数组中通过测试(函数fn内判断)的第一个元素的下标[/h1]
Array.prototype.findIndex = Array.prototype.findIndex || function findIndex(fn, ctx){ fn = fn.bind(ctx) let result; this.some((value, index, arr), thisValue) => { return fn(value, index, arr) ? (result = index, true) : false }) return result}
[h1]46、performance.timing:利用performance.timing进行性能分析[/h1]
window.onload = function(){ setTimeout(function(){ let t = performance.timing console.log('DNS查询耗时 :' + (t.domainLookupEnd - t.domainLookupStart).toFixed(0)) console.log('TCP链接耗时 :' + (t.connectEnd - t.connectStart).toFixed(0)) console.log('request请求耗时 :' + (t.responseEnd - t.responseStart).toFixed(0)) console.log('解析dom树耗时 :' + (t.domComplete - t.domInteractive).toFixed(0)) console.log('白屏时间 :' + (t.responseStart - t.navigationStart).toFixed(0)) console.log('domready时间 :' + (t.domContentLoadedEventEnd - t.navigationStart).toFixed(0)) console.log('onload时间 :' + (t.loadEventEnd - t.navigationStart).toFixed(0)) if(t = performance.memory){ console.log('js内存使用占比 :' + (t.usedJSHeapSize / t.totalJSHeapSize * 100).toFixed(2) + '%') } })}
[h1]47、禁止某些键盘事件[/h1]
document.addEventListener('keydown', function(event){ return !( 112 == event.keyCode || //F1 123 == event.keyCode || //F12 event.ctrlKey && 82 == event.keyCode || //ctrl + R event.ctrlKey && 78 == event.keyCode || //ctrl + N event.shiftKey && 121 == event.keyCode || //shift + F10 event.altKey && 115 == event.keyCode || //alt + F4 "A" == event.srcElement.tagName && event.shiftKey //shift + 点击a标签 ) || (event.returnValue = false)});
[h1]48、禁止右键、选择、复制[/h1]
['contextmenu', 'selectstart', 'copy'].forEach(function(ev){ document.addEventListener(ev, function(event){ return event.returnValue = false })});
github地址:https://github.com/hfhan/tools
推荐↓↓↓
长
按
关
注
【16个技术公众号】都在这里!
涵盖:程序员大咖、源码共读、程序员共读、数据结构与算法、黑客技术和网络安全、大数据科技、编程前端、Java、Python、Web编程开发、Android、iOS开发、Linux、数据库研发、幽默程序员等。
万水千山总是情,点个 “在看” 行不行 |
|