In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
In this issue, the editor will bring you about the 36 pieces of JavaScript functions commonly used in your work. The article is rich in content and analyzes and describes for you from a professional point of view. I hope you can get something after reading this article.
Array Array
Array deduplication
Function noRepeat (arr) {return [... new Set (arr)];}
Find the largest array
Function arrayMax (arr) {return Math.max (.arr);}
Find the smallest array
Function arrayMin (arr) {return Math.min (.arr);}
Returns the original array that has been split into size lengths
Function chunk (arr, size = 1) {return Array.from ({length: Math.ceil (arr.length / size),}, (v, I) = > arr.slice (I * size, I * size + size);}
Check the number of occurrences of an element in the array
Function countOccurrences (arr, value) {return arr.reduce ((a, v) = > (v = = value? A + 1: a + 0), 0);}
Flattened array
Default depth expand all
Function flatten (arr, depth =-1) {if (depth =-1) {return [] .concat (. Arr.map ((v) = > (Array.isArray (v)? This.flatten (v): v));} if (depth = 1) {return arr.reduce ((a, v) = > a.concat (v), []);} return arr.reduce ((a, v) = > a.concat (Array.isArray (v)? This.flatten (v, depth-1): v), []);}
Compare two arrays and return different elements
Function diffrence (arrA, arrB) {return arrA.filter ((v) = >! arrB.includes (v));}
Returns the same element in both arrays
Function intersection (arr1, arr2) {return arr2.filter ((v) = > arr1.includes (v));}
Delete n elements from the right
Function dropRight (arr, n = 0) {return n
< arr.length ? arr.slice(0, arr.length - n) : []; } 截取第一个符合条件的元素及其以后的元素 function dropElements(arr, fn) { while (arr.length && !fn(arr[0])) arr = arr.slice(1); return arr; } 返回数组中下标间隔 nth 的元素 function everyNth(arr, nth) { return arr.filter((v, i) =>I% nth = = nth-1);}
Returns the nth element in the array
Support for negative numbers
Function nthElement (arr, n = 0) {return (n > = 0? Arr.slice (n, n + 1): arr.slice (n)) [0];}
Returns the array header element
Function head (arr) {return arr [0];}
Returns the element at the end of the array
Function last (arr) {return arr [arr.length-1];}
Array disarray
Function shuffle (arr) {let array = arr; let index = array.length; while (index) {index-= 1; let randomInedx = Math.floor (Math.random () * index); let middleware = array [index]; array [index] = array [randomInedx]; array [randomInedx] = middleware;} return array;} browser object BOM
Determine whether the browser supports the CSS attribute
/ * informs the browser of the specified css attribute supported * @ param {String} key-css attribute, which is the name of the attribute and does not need to be prefixed with * @ returns {String}-supported attribute case * / function validateCssKey (key) {const jsKey = toCamelCase (key); / / some css attributes are hyphenated to form if (jsKey in document.documentElement.style) {return key;} let validKey = "" / / the attribute name is the form of prefix in js, and the attribute value is the form of prefix in css / / after trying, Webkit can also be initials webkit const prefixMap = {Webkit: "- webkit-", Moz: "- moz-", ms: "- ms-", O: "- o -",}; for (const jsPrefix in prefixMap) {const styleKey = toCamelCase (`${jsPrefix}-${jsKey}`) If (styleKey in document.documentElement.style) {validKey = prefixMap [jsPrefix] + key; break;}} return validKey;} / * converts a hyphenated string into a hump naming string * / function toCamelCase (value) {return value.replace (/-(\ w) / g, (matched, letter) = > {return letter.toUpperCase ();}) } / * check whether the browser supports a css attribute value (es6 version) * @ param {String} key-the name of the css attribute to which the checked attribute value belongs * @ param {String} value-the css attribute value to be checked (without prefix) * @ returns {String}-returns the supported attribute value of the browser * / function valiateCssValue (key, value) {const prefix = ["- o -", "- ms-" "- moz-", "- webkit-", ""] Const prefixValue = prefix.map ((item) = > {return item + value;}); const element = document.createElement ("div"); const eleStyle = element.style; / / when each prefix is applied, and finally if there is no prefix on it, see how the browser works in the end / / this is the best last element in prefix is''prefixValue.forEach ((item) = > {eleStyle [key] = item }); return eleStyle [key] } / * check whether the browser supports a css attribute value * @ param {String} key-the name of the css attribute to which the checked attribute value belongs * @ param {String} value-the css attribute value to be checked (without a prefix) * @ returns {String}-returns the supported attribute value of the browser * / function valiateCssValue (key, value) {var prefix = ["- o -", "- ms-" "- moz-", "- webkit-", ""] Var prefixValue = []; for (var I = 0; I
< prefix.length; i++) { prefixValue.push(prefix[i] + value); } var element = document.createElement("div"); var eleStyle = element.style; for (var j = 0; j < prefixValue.length; j++) { eleStyle[key] = prefixValue[j]; } return eleStyle[key]; } function validCss(key, value) { const validCss = validateCssKey(key); if (validCss) { return validCss; } return valiateCssValue(key, value); } 摘自 https://juejin.im/post/5e58f398f265da574a1eb569 返回当前网页地址 function currentURL() { return _window.location.href; } 获取滚动条位置 function getScrollPosition(el = window) { return { x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft, y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop, }; } 获取 url 中的参数 function getURLParameters(url) { return url .match(/([^?=&]+)(=([^&]*))/g) .reduce( (a, v) =>(a [v.slice (0, v.indexOf ("="))] = v.slice (v.indexOf ("=") + 1)), a), {});}
Page jump, whether it is recorded in history
Function redirect (url, asLink = true) {asLink? _ window.location.href = url: _ window.location.replace (url);}
Scroll bar back to the top animation
Function scrollToTop () {const scrollTop = document.documentElement.scrollTop | | document.body.scrollTop; if (scrollTop > 0) {window.requestAnimationFrame (scrollToTop); window.scrollTo (0, c-c / 8);} else {window.cancelAnimationFrame (scrollToTop);}}
Copy text
Function copy (str) {const el = document.createElement ("textarea"); el.value = str; el.setAttribute ("readonly", ""); el.style.position = "absolute"; el.style.left = "- 9999px"; el.style.top = "- 9999px"; document.body.appendChild (el); const selected = document.getSelection (). RangeCount > 0? Document.getSelection () .getRangeAt (0): false; el.select (); document.execCommand ("copy"); document.body.removeChild (el); if (selected) {document.getSelection () .removeAllRanges (); document.getSelection () .addRange (selected);}}
Detect the type of equipment
Function detectDeviceType () {return / Android | webOS | iPhone | iPad | iPod | BlackBerry | IEMobile | Opera Mini/i.test (navigator.userAgent)? "Mobile": "Desktop";} Cookie
Increase
Function setCookie (key, value, expiredays) {var exdate = new Date (); exdate.setDate (exdate.getDate () + expiredays); [xss_clean] = key + "=" + escape (value) + (expiredays = = null? ":"; expires= "+ exdate.toGMTString ());}
Delete
Function delCookie (name) {var exp = new Date (); exp.setTime (exp.getTime ()-1); var cval = getCookie (name); if (cval! = null) {[xss_clean] = name + "=" + cval + "; expires=" + exp.toGMTString ();}}
Check
Function getCookie (name) {var arr, reg = new RegExp ("(^ |)" + name + "= ([^;] *) (; | $)"); if ((arr = [xss_clean] .match (reg) {return arr [2];} else {return null;}} date Date
Time stamp converted to time
The default is the current time conversion result.
IsMs: whether the timestamp is millisecond
Function timestampToTime (timestamp = Date.parse (new Date ()), isMs = true) {const date = new Date (timestamp * (isMs? 1: 1000)); return `$ {date.getFullYear ()}-${date.getMonth () + 1
< 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1 }-${date.getDate()} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`; }文档对象 DOM 固定滚动条 /** * 功能描述:一些业务场景,如弹框出现时,需要禁止页面滚动,这是兼容安卓和 iOS 禁止页面滚动的解决方案 */ let scrollTop = 0; function preventScroll() { // 存储当前滚动位置 scrollTop = window.scrollY; // 将可滚动区域固定定位,可滚动区域高度为 0 后就不能滚动了 document.body.style["overflow-y"] = "hidden"; document.body.style.position = "fixed"; document.body.style.width = "100%"; document.body.style.top = -scrollTop + "px"; // document.body.style['overscroll-behavior'] = 'none' } function recoverScroll() { document.body.style["overflow-y"] = "auto"; document.body.style.position = "static"; // document.querySelector('body').style['overscroll-behavior'] = 'none' window.scrollTo(0, scrollTop); } 判断当前位置是否为页面底部 返回值为 true/false function bottomVisible() { return ( document.documentElement.clientHeight + window.scrollY >= (document.documentElement.scrollHeight | | document.documentElement.clientHeight);}
Determine whether the element is within the visual range
Whether partiallyVisible is fully visible or not
Function elementIsVisibleInViewport (el, partiallyVisible = false) {const {top, left, bottom, right} = el.getBoundingClientRect (); return partiallyVisible? (top > 0 & & top
< innerHeight) || (bottom >0 & & bottom
< innerHeight)) && ((left >0 & & left
< innerWidth) || (right >0 & & right
< innerWidth)) : top >= 0 & & left > = 0 & & bottom
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.