您好,登錄后才能下訂單哦!
這篇文章主要介紹前端開發(fā)中有哪些常用的JS功能函數(shù),文中介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們一定要看完!
25、unique
: 數(shù)組去重,返回一個新數(shù)組
function unique(arr){ if(!isArrayLink(arr)){ //不是類數(shù)組對象 return arr } let result = [] let objarr = [] let obj = Object.create(null) arr.forEach(item => { if(isStatic(item)){//是除了symbol外的原始數(shù)據(jù) let key = item + '_' + getRawType(item); if(!obj[key]){ obj[key] = true result.push(item) } }else{//引用類型及symbol if(!objarr.includes(item)){ objarr.push(item) result.push(item) } } }) return resulte}
26、Set簡單實現(xiàn)
window.Set = window.Set || (function () { function Set(arr) { this.items = arr ? unique(arr) : []; this.size = this.items.length; // Array的大小 } Set.prototype = { add: function (value) { // 添加元素,若元素已存在,則跳過,返回 Set 結(jié)構(gòu)本身。 if (!this.has(value)) { this.items.push(value); this.size++; } return this; }, clear: function () { //清除所有成員,沒有返回值。 this.items = [] this.size = 0 }, delete: function (value) { //刪除某個值,返回一個布爾值,表示刪除是否成功。 return this.items.some((v, i) => { if(v === value){ this.items.splice(i,1) return true } return false }) }, has: function (value) { //返回一個布爾值,表示該值是否為Set的成員。 return this.items.some(v => v === value) }, values: function () { return this.items }, } return Set;}());
27、repeat
:生成一個重復(fù)的字符串,有n個str組成,可修改為填充為數(shù)組等
function repeat(str, n) { let res = ''; while(n) { if(n % 2 === 1) { res += str; } if(n > 1) { str += str; } n >>= 1; } return res};//repeat('123',3) ==> 123123123
28、dateFormater
:格式化時間
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<10?'0':'') + M) .replace(/DD/g,(D<10?'0':'') + D) .replace(/HH|hh/g,(H<10?'0':'') + H) .replace(/mm/g,(m<10?'0':'') + m) .replace(/ss/g,(s<10?'0':'') + s)}// dateFormater('YYYY-MM-DD HH:mm', t) ==> 2019-06-26 18:30// dateFormater('YYYYMMDDHHmm', t) ==> 201906261830
29、dateStrForma
:將指定字符串由一種時間格式轉(zhuǎn)化為另一種。From的格式應(yīng)對應(yīng)str的位置
function dateStrForma(str, from, to){ //'20190626' 'YYYYMMDD' 'YYYY年MM月DD日' str += '' let Y = '' if(~(Y = from.indexOf('YYYY'))){ Y = str.substr(Y, 4) to = to.replace(/YYYY|yyyy/g,Y) }else if(~(Y = from.indexOf('YY'))){ Y = str.substr(Y, 2) to = to.replace(/YY|yy/g,Y) } let k,i ['M','D','H','h','m','s'].forEach(s =>{ i = from.indexOf(s+s) k = ~i ? str.substr(i, 2) : '' to = to.replace(s+s, k) }) return to}// dateStrForma('20190626', 'YYYYMMDD', 'YYYY年MM月DD日') ==> 2019年06月26日// dateStrForma('121220190626', '----YYYYMMDD', 'YYYY年MM月DD日') ==> 2019年06月26日// dateStrForma('2019年06月26日', 'YYYY年MM月DD日', 'YYYYMMDD') ==> 20190626// 一般的也可以使用正則來實現(xiàn)//'2019年06月26日'.replace(/(\d{4})年(\d{2})月(\d{2})日/, '$1-$2-$3') ==> 2019-06-26
30、getPropByPath
:根據(jù)字符串路徑獲取對象屬性:‘obj[0].count
’
function getPropByPath(obj, path, strict) { let tempObj = obj; path = path.replace(/\[(\w+)\]/g, '.$1'); //將[0]轉(zhuǎn)化為.0 path = path.replace(/^\./, ''); //去除開頭的. let keyArr = path.split('.'); //根據(jù).切割 let i = 0; for (let len = keyArr.length; i < len - 1; ++i) { if (!tempObj && !strict) break; let key = keyArr[i]; if (key in tempObj) { tempObj = tempObj[key]; } else { if (strict) {//開啟嚴(yán)格模式,沒找到對應(yīng)key值,拋出錯誤 throw new Error('please transfer a valid prop path to form item!'); } break; } } return { o: tempObj, //原始數(shù)據(jù) k: keyArr[i], //key值 v: tempObj ? tempObj[keyArr[i]] : null // key值對應(yīng)的值 };};
31、GetUrlParam
:獲取Url參數(shù),返回一個對象
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"}
32、downloadFile:base64
數(shù)據(jù)導(dǎo)出文件,文件下載
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);}}
33、toFullScreen
:全屏
function toFullScreen() {let elem = document.body; elem.webkitRequestFullScreen ? elem.webkitRequestFullScreen() : elem.mozRequestFullScreen ? elem.mozRequestFullScreen() : elem.msRequestFullscreen ? elem.msRequestFullscreen() : elem.requestFullScreen ? elem.requestFullScreen() : alert("瀏覽器不支持全屏");}
34、exitFullscreen
:退出全屏
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退出");}
35、requestAnimationFrame
:window動畫
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);}
36、_isNaN
:檢查數(shù)據(jù)是否是非數(shù)字值
function _isNaN(v){ return !(typeof v === 'string' || typeof v === 'number') || isNaN(v)}
37、max
:求取數(shù)組中非NaN數(shù)據(jù)中的最大值
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
38、min
:求取數(shù)組中非NaN數(shù)據(jù)中的最小值
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
39、random
:返回一個lower-upper直接的隨機數(shù)。(lower
、upper
無論正負(fù)與大小,但必須是非NaN的數(shù)據(jù))
function random(lower, upper) {lower = +lower || 0upper = +upper || 0return Math.random() * (upper - lower) + lower;}//random(0, 0.5) ==> 0.3567039135734613//random(2, 1) ===> 1.6718418553475423//random(-2, -1) ==> -1.4474325452361945
40、Object.keys
:返回一個由一個給定對象的自身可枚舉屬性組成的數(shù)組
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;}
41、Object.values
:返回一個給定對象自身的所有可枚舉屬性值的數(shù)組
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;}
42、arr.fill
:使用value值填充array,從start位置開始,到end位置結(jié)束(但不包含end位置),返回原數(shù)組
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]
43、arr.includes
:用來判斷一個數(shù)組是否包含一個指定的值,如果是返回true,否則返回false,可指定開始查詢的位置
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;}
44、返回數(shù)組中通過測試(函數(shù)fn內(nèi)判斷)的第一個元素的值
Array.prototype.find = Array.prototype.find || function find(fn, ctx) {ctx = ctx || this;let result;ctx.some((value, index, arr), thisValue) => {return fn(value, index, arr) ? (result = value, true) : false})return result}
45、arr.findIndex
:返回數(shù)組中通過測試(函數(shù)fn內(nèi)判斷)的第一個元素的下標(biāo)
Array.prototype.findIndex = Array.prototype.findIndex || function findIndex(fn, ctx){ ctx = ctx || this let result; ctx.some((value, index, arr), thisValue) => { return fn(value, index, arr) ? (result = index, true) : false }) return result}
46、performance.timing
:利用performance.timing
進(jìn)行性能分析
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('白屏?xí)r間 :' + (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內(nèi)存使用占比:' + (t.usedJSHeapSize / t.totalJSHeapSize * 100).toFixed(2) + '%')}})}
47、禁止某些鍵盤事件
document.addEventListener('keydown', function(event) {return !(112 == event.keyCode ||//禁止F1123 == event.keyCode ||//禁止F12event.ctrlKey && 82 == event.keyCode ||//禁止ctrl+Revent.ctrlKey && 18 == event.keyCode ||//禁止ctrl+Nevent.shiftKey && 121 == event.keyCode || //禁止shift+F10event.altKey && 115 == event.keyCode ||//禁止alt+F4"A" == event.srcElement.tagName && event.shiftKey//禁止shift+點擊a標(biāo)簽) || (event.returnValue = false)});
48、禁止右鍵、選擇、復(fù)制
['contextmenu', 'selectstart', 'copy'].forEach(function(ev) {document.addEventListener(ev, function(event) {return event.returnValue = false;})});
以上是“前端開發(fā)中有哪些常用的JS功能函數(shù)”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。