In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces the front-end development of which commonly used JS function, the article introduces in great detail, has a certain reference value, interested friends must read it!
25. Unique: array is deduplicated and a new array is returned
Function unique (arr) {if (! isArrayLink (arr)) {/ / is not a class array object return arr} let result = [] let objarr = [] let obj = Object.create (null) arr.forEach (item = > {if (isStatic (item) {/ / is the raw data let key = item +'_'+ getRawType (item) except symbol If (! obj [key]) {obj [key] = true result.push (item)}} else {/ / reference type and symbol if (! objarr.includes (item)) {objarr.push (item) result.push (item)}}) return resulte}
26. Simple implementation of Set
Window.Set = window.Set | | (function () {function Set (arr) {this.items = arr? Unique (arr): []; this.size = size of this.items.length; / / Array} Set.prototype = {add: function (value) {/ / add an element. If the element already exists, skip it and return the Set structure itself. If (! this.has (value)) {this.items.push (value); this.size++;} return this;}, clear: function () {/ / clears all members with no return value. This.items = [] this.size = 0}, delete: function (value) {/ / delete a value and return a Boolean value indicating whether the deletion is successful. Return this.items.some ((v, I) = > {if (v = value) {this.items.splice (iMagne1) return true} return false})}, has: function (value) {/ / returns a Boolean value Indicates whether the value is a member of Set. Return this.items.some (v = > v = value)}, values: function () {return this.items},} return Set;} ()
27. Repeat: generate a duplicate string consisting of n str, which can be modified to fill an array, etc.
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) = > 123123123
28. DateFormater: formatting time
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 (2Magazine 2)) .replace (/ MM/g, (M / June 26, 2019 / / dateStrForma ('June 26, 2019', 'YYYY mm month DD date' 'YYYYMMDD') = > 20190626Universe / regular can also be used to implement / /' June 26th, 2019'. Replace (/ (\ d {4}) year (\ d {2}) month (\ d {2}) day /,'$1murf / 2murf 3') = > 2019-06-26
30. GetPropByPath: get the object attribute according to the string path: 'obj [0] .count'
Function getPropByPath (obj, path, strict) {let tempObj = obj; path = path.replace (/\ [(\ w+)\] / g,'.$ 1'); / / convert [0] to .0 path = path.replace (/ ^\ /,''); / / remove the beginning. Let keyArr = path.split ('.'); / / according to. Cut 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) {//开启严格模式,没找到对应key值,抛出错误 throw new Error('please transfer a valid prop path to form item!'); } break; } } return { o: tempObj, //原始数据 k: keyArr[i], //key值 v: tempObj ? tempObj[keyArr[i]] : null // key值对应的值 };}; 31、GetUrlParam:获取Url参数,返回一个对象 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 data export file, file download
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: full screen
Function toFullScreen () {let elem = document.body; elem.webkitRequestFullScreen? Elem.webkitRequestFullScreen (): elem.mozRequestFullScreen? Elem.mozRequestFullScreen (): elem.msRequestFullscreen? Elem.msRequestFullscreen (): elem.requestFullScreen? Elem.requestFullScreen (): alert ("browser does not support full screen");}
34. ExitFullscreen: exit full screen
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 ("failed to switch, try Esc to quit");}
35. RequestAnimationFrame:window animation
Window.requestAnimationFrame = window.requestAnimationFrame | | window.webkitRequestAnimationFrame | | window.mozRequestAnimationFrame | | window.msRequestAnimationFrame | | window.oRequestAnimationFrame | | function (callback) {/ / to make the effect of setTimteout as close as possible to 60 frames per second window.setTimeout (callback, 1000 / 60);} window.cancelAnimationFrame = window.cancelAnimationFrame | | window.webkitCancelAnimationFrame | window.mozCancelAnimationFrame | | window.msCancelAnimationFrame | window.oCancelAnimationFrame | | function (id) {/ / to make setTimteout's effect as close to 60 frames per second as possible window.clearTimeout (id);}
36. _ isNaN: check whether the data is non-numeric
Function _ isNaN (v) {return! (typeof v = = 'string' | | typeof v =' number') | | isNaN (v)}
37. Max: find the maximum value in the non-NaN data in the array
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: find the minimum value in non-NaN data in the array
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: returns a random number directly from lower-upper. (lower, upper, no matter positive or negative or small, but must be non-NaN data)
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: returns an array of enumerable properties of a given object
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: returns an array of all enumerable attribute values of a given object itself
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 (objectkey))}} return result;}
42. Arr.fill: fill the array with the value value, starting at the start position and ending at the end position (but excluding the end position), returning the original array
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: used to determine whether an array contains a specified value. If true is returned, otherwise false is returned, you can specify the location to start the query.
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. Returns the value of the first element in the array that passes the test (judged in the function fn)
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: returns the subscript of the first element in the array that passes the test (judged in the function fn)
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 analysis using performance.timing
_ window.onload = function () {setTimeout (function () {let t = performance.timing) Console.log ('DNS query time:' + (t.domainLookupEnd-t.domainLookupStart). ToFixed (0)) console.log ('TCP link time:' + (t.connectEnd-t.connectStart). ToFixed (0)) console.log ('request request time:' + (t.responseEnd-t.responseStart). ToFixed (0) console.log ('time spent parsing dom tree:' + (t.domComplete-t) .domInteractive) .toFixed (0) console.log ('white screen time:' + (t.responseStart-t.navigationStart) .toFixed (0)) console.log ('domready time:' + (t.domContentLoadedEventEnd-t.navigationStart) .toFixed (0)) console.log ('onload time:' + (t.loadEventEnd-t.navigationStart). ToFixed (0)) if (t = performance.memory) {console.log ('js memory usage ratio:'+ (t.usedJSHeapSize / t.totalJSHeapSize * 100) .tofixed (2) +'%'}})})}
47. Prohibit certain keyboard events
Document.addEventListener ('keydown' Function (event) {return! (1212 = = event.keyCode | | / prohibit F1123 = = event.keyCode | | / prohibit F12event.ctrlKey & & 82 = = event.keyCode | | / prohibit ctrl+Revent.ctrlKey & & 18 = = event.keyCode | | / prohibit ctrl+Nevent.shiftKey & & 18 = = event.keyCode | | / prohibit shift+F10event.altKey & & 115 = = event.keyCode | | / prohibit alt+F4 "A" = = event.srcElement.tagName & & event.shiftKey// prohibit shift+ from clicking on the a tag) | | (event.returnValue = false)})
48. Right-click, select and copy are prohibited
['contextmenu',' selectstart', 'copy'] .forEach (function (ev) {document.addEventListener (ev, function (event) {return event.returnValue = false;})); these are all the contents of the article "what are the commonly used JS functions in front-end development? thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.