Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the JS tools used at high frequency?

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces the high-frequency use of JS tools what the relevant knowledge, the content is detailed and easy to understand, the operation is simple and fast, with a certain reference value, I believe that after reading this high-frequency use of JS tools which articles will have a harvest, let's take a look.

1. Back to the top.

Go back to the top scheme more smoothly

Const scrollToTop = () = > {const c = document.documentElement.scrollTop | | document.body.scrollTop; if (c > 0) {window.requestAnimationFrame (scrollToTop); window.scrollTo (0, c-c / 8);}; scrollToTop (); 2. Delete the specified item in the array

The tool method that is often used in the project, passes in the target array and the target element, and returns a new array.

Const removeArray = (arr, item) = > {let result = []; let index =-1; if (! (arr! = null & & arr.length)) {return result;} result = arr; if (Object.prototype.toString.call (item) = = "[object Object]") {index = arr.findIndex ((I) = > isEqualObject (I, item));} else {index = arr.findIndex ((I) = > I = = item) } if (index >-1) result.splice (index, 1); return result;}; const isEqualObject = (obja, objb) = > {const aProps = Object.getOwnPropertyNames (obja); const bProps = Object.getOwnPropertyNames (objb); if (aProps.length! = bProps.length) {return false;} for (let I = 0; I

< aProps.length; i++) { let propName = aProps[i]; let propA = obja[propName]; let propB = objb[propName]; if (!objb.hasOwnProperty(propName)) return false; if (propA instanceof Object) { if (!this.isEqualObject(propA, propB)) { return false; } } else if (propA !== propB) { return false; } } return true;};removeArray([{ name: 1 }, { name: "1" }, 1, "1"], { name: "1" });3. 获取 url 某一个参数 用于获取url传参获取参数 const getUrlParam = (key) =>

{const url = new URL_ (window.location.href); const value = url.searchParams.get (key); return value;}; getUrlParam ("id"); 4. Copy text

Copy all kinds of custom text with high browser compatibility

Const copyText = (text) = > {const clipboardData = window.clipboardData; if (clipboardData) {clipboardData.clearData (); clipboardData.setData ("Text", text); return true;} else if (document.execCommand) {const el = document.createElement ("textarea"); el.value = text; el.setAttribute ("readonly", ""); el.style.position = "absolute"; el.style.left = "- 9999px" Document.body.appendChild (el); el.select (); document.execCommand ("copy"); document.body.removeChild (el); return true;} return false;}; copyText ("Test"); 5. Prohibit copying text body {user-select: none;-moz-user-select: none;-webkit-user-select: none;-ms-user-select: none;} / disable right-click menu document.body.oncontextmenu = (e) = > {return false;}; / / disable text document.body.onselectstart = (e) = > {return false;}; / / prohibit copying document.body.oncopy = (e) = > {return false;} / / prohibit cutting document.body.oncut = (e) = > {return false;}; / / prohibit pasting document.body.onpaste = (e) = > {return false;}; 6. Copy text with copyright information document.body.oncopy = (event) = > {event.preventDefault (); const clipboardData = event.clipboardData; let text = window.getSelection (0). ToString (); text = `$ {text}\ nThis is the inserted text\ n`; if (clipboardData) {clipboardData.clearData (); clipboardData.setData ("Text", text); return true } else if (document.execCommand) {window.clipboardData.setData ("Text", text);} return false;}; 7. Determine data types and data values

A commonly used tool class for verifying whether data is legal

/ / whether it is a string function isString (obj) {return Object.prototype.toString.call (obj) = = "[object String]";} / whether it is a numeric function isNumber (obj) {return (Object.prototype.toString.call (obj) = = "[object Number]" & & / [\ d\.] + / .test (String (obj) } / / whether it is a Boolean function isBoolean (obj) {return Object.prototype.toString.call (obj) = = "[object Boolean]";} / whether it is an array function isArray (obj) {return Object.prototype.toString.call (obj) = = "[object Array]";} / whether it is an object function isObject (arg) {if (arg = = null) {return false;} else {return Object.prototype.toString.call (arg) = "[object Object]" }} / / whether it is a method function isFunction (arg) {const type = Object.prototype.toString.call (arg); return type = = "[object Function]" | | type = = "[object AsyncFunction]";} / / whether it is a time format function isDate (obj) {return Object.prototype.toString.call (obj) = = "[object Date]";} / / whether it is a time undefinedfunction isUndefined (arg) {return arg = void 0 } / / whether the object function isEmptyObject (arg) {if (isObject (arg)) {for (var key in arg) {if (Object.prototype.hasOwnProperty.call (arg, key)) {return false;}} return true;} return false;} 8. Ua environment judgment

It is used to distinguish different platforms and is often used to adapt on iOS.

Const getUaInfo = () = > {const ua = navigator.userAgent.toLowerCase (); const Agents = ["Android", "android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod",]; let isPc = true; for (var I = 0; I

< Agents.length; i++) { if (userAgentInfo.includes(Agents[i])) { isPc = false; break; } } return { // 是不是ios isIos: !!ua.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) || ua.includes("mac os x"), // 是不是安卓 isAndroid: ua.includes("android") || ua.includes("Android") || ua.includes("Adr"), // 是不是微信环境 isWeixin: ua.match(/MicroMessenger/i) == "micromessenger", // 是不是电脑端 isPc: isPc, };};9. 时间格式转换// Date转yyyy-MM-dd HH:mm:ssconst filterTimeByDate = (date, pattern = "yyyy-MM-dd HH:mm:ss") =>

{const o = {"M +": date.getMonth () + 1, "d +": date.getDate (), "H+": date.getHours (), "m +": date.getMinutes (), "s +": date.getSeconds (), "Q +": Math.floor ((date.getMonth () + 3) / 3), S: date.getMilliseconds (),} If (/ (y +) / .test (pattern)) {pattern = pattern.replace (RegExp.$1, (date.getFullYear () + "). Substr (4-RegExp.$1.length));} for (var k in o) {if (new RegExp (" ("+ k +")) .test (pattern)) {pattern = pattern.replace (RegExp.$1, RegExp.$1.length = = 1? O [k]: ("00" + o [k]) .substr (("" + o [k]) .length);}} return pattern;}; filterTimeByDate (new Date ()); / / timestamp to yyyy-MM-dd HH:mm:ssconst timestampToTime = (timestamp) = > {const date = new Date (String (timestamp) .length > 10? Timestamp: timestamp * 1000); / / 10-bit timestamp requires * 1000, and 13-bit timestamp does not need to be multiplied by 1000 const Y = date.getFullYear () + "-"; const M = (date.getMonth () + 1)

< 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + "-"; const D = (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " "; const h = (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":"; const m = (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) + ":"; const s = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds(); return Y + M + D + h + m + s;};timestampToTime(new Date().getTime());// yyyy-MM-dd HH:mm:ss转时间戳const timeToTimestamp = (time, isMilli = true) =>

{const timestamp = new Date (time). GetTime (); / / 10-bit timestamp requires * 1000, and 13-bit timestamp does not need to be multiplied by 1000 return isMilli? Timestamp: timestamp / 1000;}; timeToTimestamp ("2022-04-26 10:11:11"); 10. Function anti-shake const debounce = (fn, delay) = > {let timer = null; return function (e) {clearTimeout (timer); timer = setTimeout () = > {fn.apply (this, arguments);}, delay);};}; document.addEventListener ("scroll", debounce (function () {console.log ("execution");}, 2000)); 11. Full screen / exit full screen function toFullScreen () {let = document.documentElement; el.webkitRequestFullScreen? El.webkitRequestFullScreen (): el.mozRequestFullScreen? El.mozRequestFullScreen (): el.msRequestFullscreen? El.msRequestFullscreen (): el.requestFullScreen? El.requestFullScreen (): alert ("current browser does not support this feature");} function exitFullscreen () {let el = document; el.webkitCancelFullScreen? El.webkitCancelFullScreen (): el.mozCancelFullScreen? El.mozCancelFullScreen (): el.cancelFullScreen? El.cancelFullScreen (): el.msExitFullscreen? El.msExitFullscreen (): el.exitFullscreen? El.exitFullscreen (): alert ("this feature is not supported by the current browser");} 12. Disable opening the console for debugging

It is used to prevent some users from attacking the server through the source code, increasing the difficulty of cracking.

SetInterval (function () {check ();}, 4000); const check = () = > {function doCheck (a) {if (("" + a / a) ["length"]! = = 1 | a% 20 = 0) {(function () {} ["constructor"] ("debugger") ());} else {(function () {} ["constructor"] ("debugger") ());} doCheck (+ + a) } try {doCheck (0);} catch (err) {}}; check (); 13. Password strength display const checkPwd = (str) = > {let Lv = 0; if (str.length)

< 6) { return Lv; } if (/[0-9]/.test(str)) { Lv++; } if (/[a-z]/.test(str)) { Lv++; } if (/[A-Z]/.test(str)) { Lv++; } if (/[\.|-|_]/.test(str)) { Lv++; } return Lv;};14. 五星好评const getRate = (rate = 0) =>

{return "★☆" .slice (5-rate, 10-rate);}; getRate (3); 15. Keep n decimal places const filterToFixed = > (num, n = 2) {return parseFloat (num.toFixed (n), 10);} 16. The amount is capitalized.

Tools and methods commonly used in order modules in mall projects

Const convertCurrency = (money) = > the number of {/ / Chinese characters const cnNums = new Array ("zero", "one", "II", "three", "restaurant", "Wu", "Lu", "Qi", "Qi", "Jiu"); / / basic unit const cnIntRadice = new Array ("", "pick up", "hundred", "thousand") / / the corresponding integer part expansion unit const cnIntUnits = new Array ("", "ten thousand", "billion", "megabyte"); / / the corresponding decimal part unit const cnDecUnits = new Array ("angle", "minute", "millimeter", "centimeter"); / / the character const cnInteger = "integer" followed by the integer amount; / / the unit const cnIntLast after the integer type is "yuan" / / maximum processed number const maxNum = 9999999999999999999999; / / amount integer part let integerNum; / / amount decimal part let decimalNum; / / output Chinese amount string let chineseStr = ""; / / the array used after separating the amount. The predefined let parts; / / input parameter is null if (money = ") {return";} money = parseFloat (money). If (money > = maxNum) {return ";} / / the parameter passed in is 0 case if (money = = 0) {chineseStr = cnNums [0] + cnIntLast + cnInteger; return chineseStr;} / / converted to the string money = money.toString () / / indexOf detects the first occurrence of a character in a string and returns the index value (starting from 0)-1 represents no if (money.indexOf (".") = =-1) {integerNum = money; decimalNum = "";} else {parts = money.split ("."); integerNum = parts [0]; decimalNum = parts [1] .substr (0,4) } / / convert integer part if (parseInt (integerNum, 10) > 0) {let zeroCount = 0; let IntLen = integerNum.length; for (let I = 0; I

< IntLen; i++) { let n = integerNum.substr(i, 1); let p = IntLen - i - 1; let q = p / 4; let m = p % 4; if (n == "0") { zeroCount++; } else { if (zeroCount >

0) {chineseStr + = cnNums [0];} zeroCount = 0; chineseStr + = chineseStr [parseInt (n)] + cnIntRadice [m];} if (m = = 0 & & zeroCount

< 4) { chineseStr += cnIntUnits[q]; } } // 最后+ 元 chineseStr += cnIntLast; } // 转换小数部分 if (decimalNum != "") { let decLen = decimalNum.length; for (let i = 0; i < decLen; i++) { let n = decimalNum.substr(i, 1); if (n != "0") { chineseStr += cnNums[Number(n)] + cnDecUnits[i]; } } } if (chineseStr == "") { chineseStr += cnNums[0] + cnIntLast + cnInteger; } else if (decimalNum == "") { chineseStr += cnInteger; } return chineseStr;};17. 常用正则判断// 校验昵称为2-9位中文const validateName = (name) =>

{const reg = / ^ [\ u4e00 -\ u9fa5] {2 9} $/; return reg.test (name);}; / / check cell phone number const validateMobile = (mobile) = > {const reg = / ^ 1 [3L4, 55, 77, 89]\ d {9} $/; return reg.test (mobile);} / / verify the password consisting of uppercase and lowercase underscores from 6 to 18 characters const validatePassword = (password) = > {const reg = / ^ [a-zA-Z0-9 _] {6Cini 18} $/; return reg.test (password);}; / / check ID number const validateCardId = (cardId) = > {const reg = / (^\ d {15} $) | (^\ d {18} $) | (^\ d {17} (\ d | X | x) $) /; return reg.test (cardId) }; 18. Solve the problem of loss of operation accuracy

It is used to solve the problem of loss of accuracy when calculating the amount at the front end.

Const calculation = {/ / addition plus (arg1, arg2) {var R1, R2, m; try {R1 = arg1.toString (). Split (".") [1] .length;} catch (e) {R1 = 0;} try {R2 = arg2.toString (). Split (".") [1] .length;} catch (e) {R2 = 0 } m = Math.pow (10, Math.max (R1, R2); return (arg1 * m + arg2 * m) / m;}, / / subtract subtract (arg1, arg2) {var R1, R2, m, n; try {R1 = arg1.toString (). Split (".") [1] .length;} catch (e) {R1 = 0 } try {R2 = arg2.toString (). Split (".") [1] .length;} catch (e) {R2 = 0;} m = Math.pow (10, Math.max (R1, R2)); n = R1 > = R2? R1: R2; return ((arg1 * m-arg2 * m) / m) .tofixed (n);}, / multiplicative multiply (arg1, arg2) {var m = 0, S1 = arg1.toString (), S2 = arg2.toString (); try {m + = s1.split (".") [1] .length;} catch (e) {} try {m + = s2.split (".") [1] .length } catch (e) {} return ((Number (s1.replace (".", ")) * Number (s2.replace (". ",")) / Math.pow (10, m));}, / / divide divide (arg1, arg2) {var T1 = 0, T2 = 0, R1, R2 Try {T1 = arg1.toString (). Split (".") [1] .length;} catch (e) {} try {T2 = arg2.toString (). Split (".") [1] .length;} catch (e) {} R1 = Number (arg1.toString (). Replace (".")); R2 = Number (arg2.toString (). Replace (".", ")) Return (R1 / R2) * Math.pow (10, T2-T1);},}; this is the end of the article on "what are the JS tools used at high frequency?" Thank you for reading! I believe you all have a certain understanding of the knowledge of "what are the JS tools used in high frequency". If you want to learn more, you are 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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report