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 fragments of JavaScript functions commonly used in 36 jobs?

2025-04-09 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

What this article shares to you is about 36 pieces of JavaScript function commonly used in your work. The editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article. Without saying much, let's take a look at it.

Array Array

Array deduplication

FunctionnoRepeat (arr) {

Return [. NewSet (arr)]

}

Find the largest array

FunctionarrayMax (arr) {

ReturnMath.max (. Arr)

}

Find the smallest array

FunctionarrayMin (arr) {

ReturnMath.min (. Arr)

}

Returns the original array that has been split into size lengths

Functionchunk (arr, size = 1) {

ReturnArray.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

FunctioncountOccurrences (arr, value) {

Returnarr.reduce ((a, v) = > (v = value? A + 1: a + 0), 0)

}

Flattened array

Default depth expand all

Functionflatten (arr, depth =-1) {

If (depth = =-1) {

Return [] .concat (

... arr.map ((v) = > (Array.isArray (v)? this.flatten (v): v))

);

}

If (depth = 1) {

Returnarr.reduce ((a, v) = > a.concat (v), [])

}

Returnarr.reduce (

(a, v) = > a.concat (Array.isArray (v)? this.flatten (v, depth-1): v)

[]

);

}

Compare two arrays and return different elements

Here the editor has built a front-end learning and exchange QQ group: 132667127, I have sorted out the latest front-end materials and advanced development tutorials, if you want, you can join the group to learn and communicate together.

Functiondiffrence (arrA, arrB) {

ReturnarrA.filter ((v) = >! arrB.includes (v))

}

Returns the same element in both arrays

Functionintersection (arr1, arr2) {

Returnarr2.filter ((v) = > arr1.includes (v))

}

Delete n elements from the right

FunctiondropRight (arr, n = 0) {

Returnn

< arr.length ? arr.slice(0, arr.length - n) : []; } 截取第一个符合条件的元素及其以后的元素 functiondropElements(arr, fn){ while(arr.length && !fn(arr[0])) arr = arr.slice(1); returnarr; } 返回数组中下标间隔 nth 的元素 functioneveryNth(arr, nth){ returnarr.filter((v, i) =>

I% nth = nth-1)

}

Returns the nth element in the array

Support for negative numbers

FunctionnthElement (arr, n = 0) {

Return (n > = 0? Arr.slice (n, n + 1): arr.slice (n)) [0]

}

Returns the array header element

Functionhead (arr) {

Returnarr [0]

}

Returns the element at the end of the array

Functionlast (arr) {

Returnarr [arr.length-1]

}

Array disarray

Functionshuffle (arr) {

Letarray= arr

Let index = array.length

While (index) {

Index-= 1

Let randomInedx = Math.floor (Math.random () * index)

Let middleware = array [index]

Array [index] = Array [independent Inedx]

Array [randomInedx] = middleware

}

Returnarray

}

Browser object BOM

Determine whether the browser supports the CSS attribute

/ * *

* inform the browser of the specified css attributes supported

* @ param {String} key-css attribute, which is the name of the attribute and does not require a prefix

* @ returns {String}-supported properties

, /

FunctionvalidateCssKey (key) {

Const jsKey = toCamelCase (key); / / some css attributes are hyphenated

If (jsKeyindocument.documentElement.style) {

Returnkey

}

Let validKey = ""

/ / the attribute name is the form of the prefix in js, and the attribute value is the form of the prefix in css

/ / after trying, Webkit is also a lowercase webkit.

Const prefixMap = {

Webkit: "- webkit-"

Moz: "- moz-"

Ms: "- ms-"

O: "- o -"

}

For (const jsPrefixinprefixMap) {

Const styleKey = toCamelCase (`${jsPrefix}-${jsKey}`)

If (styleKeyindocument.documentElement.style) {

ValidKey = prefixMap [jsPrefix] + key

Break

}

}

ReturnvalidKey

}

/ * *

* convert a hyphenated string into a hump nomenclature

, /

FunctiontoCamelCase (value) {

Returnvalue.replace (/-(\ w) / g, (matched, letter) = > {

Returnletter.toUpperCase ()

});

}

/ * *

* check whether the browser supports a css attribute value (es6 version)

* @ param {String} key-the name of the css attribute to which the value of the property is checked

* @ param {String} value-the value of the css attribute to check (without a prefix)

* @ returns {String}-returns the property values supported by the browser

, /

FunctionvaliateCssValue (key, value) {

Const prefix = ["- o -", "- ms-", "- moz-", "- webkit-", ""]

Const prefixValue = prefix.map ((item) = > {

Returnitem + value

});

Const element = document.createElement ("div")

Const eleStyle = element.style

/ / apply each prefix, and finally apply the situation where there is no prefix, and see how the browser works in the end.

/ / this is the best last element in prefix is''.

PrefixValue.forEach ((item) = > {

EleStyle [key] = item

});

ReturneleStyle [key]

}

/ * *

* check whether the browser supports a css attribute value

* @ param {String} key-the name of the css attribute to which the value of the property is checked

* @ param {String} value-the value of the css attribute to check (without a prefix)

* @ returns {String}-returns the property values supported by the browser

, /

FunctionvaliateCssValue (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]; } returneleStyle[key]; } functionvalidCss(key, value){ const validCss = validateCssKey(key); if(validCss) { returnvalidCss; } returnvaliateCssValue(key, value); } 返回当前网页地址 functioncurrentURL(){ return_window.location.href; } 获取滚动条位置 functiongetScrollPosition(el = window){ return{ x: el.pageXOffset !==undefined? el.pageXOffset : el.scrollLeft, y: el.pageYOffset !==undefined? el.pageYOffset : el.scrollTop, }; } 获取 url 中的参数 functiongetURLParameters(url){ returnurl .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

Functionredirect (url, asLink = true) {

AsLink? _ (window.location.href = url): _ window.location.replace (url)

}

Scroll bar back to the top animation

FunctionscrollToTop () {

ConstscrollTop =

Document.documentElement.scrollTop | | document.body.scrollTop

If (scrollTop > 0) {

Window.requestAnimationFrame (scrollToTop)

Window.scrollTo (0, c-c / 8)

} else {

Window.cancelAnimationFrame (scrollToTop)

}

}

Copy text

Functioncopy (str) {

Constel = 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)

Constselected =

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

FunctiondetectDeviceType () {

Return/Android | webOS | iPhone | iPad | iPod | BlackBerry | IEMobile | Opera Mini/i.test (

Navigator.userAgent

)

? "Mobile"

"Desktop"

}

Cookie

Increase

FunctionsetCookie (key, value, expiredays) {

Varexdate = newDate ()

Exdate.setDate (exdate.getDate () + expiredays)

[xss_clean] =

Key +

= "+

Escape (value) +

(expiredays = = null? ":"; expires= "+ exdate.toGMTString ())

}

Delete

FunctiondelCookie (name) {

Varexp = newDate ()

Exp.setTime (exp.getTime () 1)

Varcval = getCookie (name)

If (cval! = null) {

[xss_clean] = name + "=" + cval + "; expires=" + exp.toGMTString ()

}

}

Check

FunctiongetCookie (name) {

Vararr

Reg = newRegExp ("(^ |)" + name + "= ([^;] *) (; | $)")

If ((arr = [xss_clean] .match (reg) {

Returnarr [2]

} else {

Returnnull

}

}

Date Date

Time stamp converted to time

The default is the current time conversion result.

IsMs: whether the timestamp is millisecond

FunctiontimestampToTime (timestamp = Date.parse (newDate ()), isMs = true) {

Constdate = newDate (timestamp * (isMs? 1pur1000))

Roomn`$ {date.getFullYear ()}-${

Date.getMonth () + 1 =

(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 ()

ReturnpartiallyVisible

? ((top > zero & top)

< innerHeight) || (bottom >

Zero & bottom

< innerHeight)) && ((left>

0&&left

< innerWidth) || (right>

0&&right

< innerWidth)) : top >

= 0&&left > = zero & 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.

Share To

Development

Wechat

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

12
Report