[Common front-end JavaScript method encapsulation]
1. Enter a value and return its data type
function type(para) {
return Object.prototype.toString.call(para)
}
Copy the code
2. Array deduplication
function unique1(arr) { return [...new Set(arr)] } function unique2(arr) { var obj = {}; return arr.filter(ele => { if (! obj[ele]) { obj[ele] = true; return true; } }) } function unique3(arr) { var result = []; arr.forEach(ele => { if (result.indexOf(ele) == -1) { result.push(ele) } }) return result; }Copy the code
3. Deduplication of the string
String.prototype.unique = function () { var obj = {}, str = '', len = this.length; for (var i = 0; i < len; i++) { if (! obj[this[i]]) { str += this[i]; obj[this[i]] = true; } } return str; } # # # # # # / / remove the continuous string function uniq (STR) {return STR. Replace (/ \ (\ w) + 1 / g, '$1')}Copy the code
4. Deep copy shallow copy
/ / deep cloning (deep cloning does not consider function) function deepClone (obj, result) {var result = result | | {}; for (var prop in obj) { if (obj.hasOwnProperty(prop)) { if (typeof obj[prop] == 'object' && obj[prop] ! = = null) {/ / reference value (obj/array) and not null if (Object. The prototype. ToString. Call (obj) [prop] = = '[Object Object]') {/ / Object result[prop] = {}; } else {// array result[prop] = []; } deepClone(obj[prop], result[prop])} else {// original value or func result[prop] = obj[prop]}} return result; } function deepClone(target) {if (typeof (target)! == 'object') { return target; } var result; If (Object. The prototype. ToString. Call (target) = = '[Object Array]') {/ / Array result = []} else {/ / Object result = {}; } for (var prop in target) { if (target.hasOwnProperty(prop)) { result[prop] = deepClone(target[prop]) } } return result; } var o1 = json.parse (json.stringify (obj1));Copy the code
5. Reverse underlying principle and extension
/ / change the original Array Array. Prototype. MyReverse = function () {var len = this. Length; for (var i = 0; i < len; i++) { var temp = this[i]; this[i] = this[len - 1 - i]; this[len - 1 - i] = temp; } return this; }Copy the code
6. Inheritance of the Holy Grail mode
function inherit(Target, Origin) { function F() {}; F.prototype = Origin.prototype; Target.prototype = new F(); Target.prototype.constructor = Target; // The final prototype points to target.prop.uber = origine.prototype; }Copy the code
7. Find the first occurrence of a letter in a string
String.prototype.firstAppear = function () { var obj = {}, len = this.length; for (var i = 0; i < len; i++) { if (obj[this[i]]) { obj[this[i]]++; } else { obj[this[i]] = 1; } } for (var prop in obj) { if (obj[prop] == 1) { return prop; }}}Copy the code
Find the NTH parent of the element
function parents(ele, n) {
while (ele && n) {
ele = ele.parentElement ? ele.parentElement : ele.parentNode;
n--;
}
return ele;
}
Copy the code
Returns the NTH sibling of the element
function retSibling(e, n) { while (e && n) { if (n > 0) { if (e.nextElementSibling) { e = e.nextElementSibling; } else { for (e = e.nextSibling; e && e.nodeType ! = = 1; e = e.nextSibling); } n--; } else { if (e.previousElementSibling) { e = e.previousElementSibling; } else { for (e = e.previousElementSibling; e && e.nodeType ! = = 1; e = e.previousElementSibling); } n++; } } return e; }Copy the code
10. Package MyChildren to solve browser compatibility problems
function myChildren(e) {
var children = e.childNodes,
arr = [],
len = children.length;
for (var i = 0; i < len; i++) {
if (children[i].nodeType === 1) {
arr.push(children[i])
}
}
return arr;
}
Copy the code
11. Determine if the element has children
function hasChildren(e) {
var children = e.childNodes,
len = children.length;
for (var i = 0; i < len; i++) {
if (children[i].nodeType === 1) {
return true;
}
}
return false;
}
Copy the code
12. I insert one element after another
Element.prototype.insertAfter = function (target, elen) { var nextElen = elen.nextElenmentSibling; if (nextElen == null) { this.appendChild(target); } else { this.insertBefore(target, nextElen); }}Copy the code
13, return the current time (year month day hour minute second)
function getDateTime() { var date = new Date(), year = date.getFullYear(), month = date.getMonth() + 1, day = date.getDate(), hour = date.getHours() + 1, minute = date.getMinutes(), second = date.getSeconds(); month = checkTime(month); day = checkTime(day); hour = checkTime(hour); minute = checkTime(minute); second = checkTime(second); function checkTime(i) { if (i < 10) { i = "0" + i; } return i; } return "" + year + month + day + hour + hour + minute + second + second}Copy the code
14. Get the scrolling distance of the scroll bar
function getScrollOffset() {
if (window.pageXOffset) {
return {
x: window.pageXOffset,
y: window.pageYOffset
}
} else {
return {
x: document.body.scrollLeft + document.documentElement.scrollLeft,
y: document.body.scrollTop + document.documentElement.scrollTop
}
}
}
Copy the code
15. Get the size of the viewport
function getViewportOffset() { if (window.innerWidth) { return { w: window.innerWidth, h: If (document.compatMode === "BackCompat") {// Eccentric mode return {w: Document. Body. ClientWidth, h: the document body. ClientHeight}} else {/ / standard model return {w: document.documentElement.clientWidth, h: document.documentElement.clientHeight } } } }Copy the code
Get any attributes of any element
function getStyle(elem, prop) {
return window.getComputedStyle ? window.getComputedStyle(elem, null)[prop] : elem.currentStyle[prop]
}
Copy the code
Compatible code for binding events
Function addEventListener(elem, type, handle) {if (elem. AddEventListener) {if (elem. false); } else if (elem. AttachEvent) {//ie6 elem. AttachEvent ('on' + type, function () {handle.call(elem); }) } else { elem['on' + type] = handle; }}Copy the code
18. Untying events
Function removeEvent(elem, type, handle) {if (elem. RemoveEventListener) {if (elem. handle, false); } else if (elem.detachevent) {//ie6 to ie8 elem.detachevent ('on' + type, handle); } else { elem['on' + type] = null; }}Copy the code
19. Cancel bubbling compatibility code
function stopBubble(e) { if (e && e.stopPropagation) { e.stopPropagation(); } else { window.event.cancelBubble = true; }}Copy the code
Check if the string is palindrome
function isPalina(str) { if (Object.prototype.toString.call(str) ! == '[object String]') { return false; } var len = str.length; for (var i = 0; i < len / 2; i++) { if (str[i] ! = str[len - 1 - i]) { return false; } } return true; }Copy the code
21. Check if the string is palindrome
function isPalindrome(str) {
str = str.replace(/\W/g, '').toLowerCase();
console.log(str)
return (str == str.split('').reverse().join(''))
}
Copy the code
22, compatible with getElementsByClassName method
Element.prototype.getElementsByClassName = Document.prototype.getElementsByClassName = function (_className) {
var allDomArray = document.getElementsByTagName('*');
var lastDomArray = [];
function trimSpace(strClass) {
var reg = /\s+/g;
return strClass.replace(reg, ' ').trim()
}
for (var i = 0; i < allDomArray.length; i++) {
var classArray = trimSpace(allDomArray[i].className).split(' ');
for (var j = 0; j < classArray.length; j++) {
if (classArray[j] == _className) {
lastDomArray.push(allDomArray[i]);
break;
}
}
}
return lastDomArray;
}
Copy the code
23. Motion function
function animate(obj, json, callback) { clearInterval(obj.timer); var speed, current; obj.timer = setInterval(function () { var lock = true; for (var prop in json) { if (prop == 'opacity') { current = parseFloat(window.getComputedStyle(obj, null)[prop]) * 100; } else { current = parseInt(window.getComputedStyle(obj, null)[prop]); } speed = (json[prop] - current) / 7; speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed); if (prop == 'opacity') { obj.style[prop] = (current + speed) / 100; } else { obj.style[prop] = current + speed + 'px'; } if (current ! = json[prop]) { lock = false; } } if (lock) { clearInterval(obj.timer); typeof callback == 'function' ? callback() : ''; 30)}}},Copy the code
24. Elastic exercise
function ElasticMovement(obj, target) { clearInterval(obj.timer); Var iSpeed = 40, a, u = 0.8; obj.timer = setInterval(function () { a = (target - obj.offsetLeft) / 8; iSpeed = iSpeed + a; iSpeed = iSpeed * u; if (Math.abs(iSpeed) <= 1 && Math.abs(a) <= 1) { console.log('over') clearInterval(obj.timer); obj.style.left = target + 'px'; } else { obj.style.left = obj.offsetLeft + iSpeed + 'px'; }}, 30); }Copy the code
25. Encapsulate your own forEach methods
Array.prototype.myForEach = function (func, obj) {
var len = this.length;
var _this = arguments[1] ? arguments[1] : window;
// var _this=arguments[1]||window;
for (var i = 0; i < len; i++) {
func.call(_this, this[i], i, this)
}
}
Copy the code
26. Encapsulate your own filter method
Array.prototype.myFilter = function (func, obj) {
var len = this.length;
var arr = [];
var _this = arguments[1] || window;
for (var i = 0; i < len; i++) {
func.call(_this, this[i], i, this) && arr.push(this[i]);
}
return arr;
}
Copy the code
27, Array map method
Array.prototype.myMap = function (func) {
var arr = [];
var len = this.length;
var _this = arguments[1] || window;
for (var i = 0; i < len; i++) {
arr.push(func.call(_this, this[i], i, this));
}
return arr;
}
Copy the code
Array every method
Array.prototype.myEvery = function (func) {
var flag = true;
var len = this.length;
var _this = arguments[1] || window;
for (var i = 0; i < len; i++) {
if (func.apply(_this, [this[i], i, this]) == false) {
flag = false;
break;
}
}
return flag;
}
Copy the code
29, Array reduce method
Array.prototype.myReduce = function (func, initialValue) { var len = this.length, nextValue, i; if (! InitialValue) {nextValue = this[0]; i = 1; } else {nextValue = initialValue; i = 0; } for (; i < len; i++) { nextValue = func(nextValue, this[i], i, this); } return nextValue; }Copy the code
30. Get url parameters (1)
function getWindonHref() { var sHref = window.location.href; var args = sHref.split('? '); if (args[0] === sHref) { return ''; } var hrefarr = args[1].split('#')[0].split('&'); var obj = {}; for (var i = 0; i < hrefarr.length; i++) { hrefarr[i] = hrefarr[i].split('='); obj[hrefarr[i][0]] = hrefarr[i][1]; } return obj; }Copy the code
31, Array sort
If (arr. Length <= 1) {return arr; if (arr. Length <= 1) {return arr; } var left = [], right = []; var pIndex = Math.floor(arr.length / 2); var p = arr.splice(pIndex, 1)[0]; for (var i = 0; i < arr.length; i++) { if (arr[i] <= p) { left.push(arr[i]); } else { right.push(arr[i]); }} // Recursive return quickArr(left). Concat ([p], quickArr(right)); } function bubbleSort(arr) {for (var I = 0; i < arr.length - 1; i++) { for (var j = i + 1; j < arr.length; j++) { if (arr[i] > arr[j]) { var temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } } return arr; } function bubbleSort(arr) { var len = arr.length; for (var i = 0; i < len - 1; i++) { for (var j = 0; j < len - 1 - i; j++) { if (arr[j] > arr[j + 1]) { var temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } return arr; }Copy the code
Traverse the Dom tree
// Given a DOM element on a page, the element itself and all its descendants (not just its immediate children) will be accessed. Function traverse(element, callback) {callback(element); var list = element.children; for (var i = 0; i < list.length; i++) { traverse(list[i], callback); }}Copy the code
33. Native JS encapsulates Ajax (1)
function ajax(method, url, callback, data, flag) {
var xhr;
flag = flag || true;
method = method.toUpperCase();
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject('Microsoft.XMLHttp');
}
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(2)
callback(xhr.responseText);
}
}
if (method == 'GET') {
var date = new Date(),
timer = date.getTime();
xhr.open('GET', url + '?' + data + '&timer' + timer, flag);
xhr.send()
} else if (method == 'POST') {
xhr.open('POST', url, flag);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(data);
}
}
Copy the code
Load script asynchronously
function loadScript(url, callback) { var oscript = document.createElement('script'); If (oscript. ReadyState) {/ / Internet explorer and the following version oscript onreadystatechange = function () {if (oscript. The readyState = = = 'complete' || oscript.readyState === 'loaded') { callback(); } } } else { oscript.onload = function () { callback() }; } oscript.src = url; document.body.appendChild(oscript); }Copy the code
Cookie management
var cookie = { set: function (name, value, time) { document.cookie = name + '=' + value + '; max-age=' + time; return this; }, remove: function (name) { return this.setCookie(name, '', -1); }, get: function (name, callback) { var allCookieArr = document.cookie.split('; '); for (var i = 0; i < allCookieArr.length; i++) { var itemCookieArr = allCookieArr[i].split('='); if (itemCookieArr[0] === name) { return itemCookieArr[1] } } return undefined; }}Copy the code
Implement bind()
Function.prototype.myBind = function (target) {
var target = target || window;
var _args1 = [].slice.call(arguments, 1);
var self = this;
var temp = function () {};
var F = function () {
var _args2 = [].slice.call(arguments, 0);
var parasArr = _args1.concat(_args2);
return self.apply(this instanceof temp ? this : target, parasArr)
}
temp.prototype = self.prototype;
F.prototype = new temp();
return F;
}
Copy the code
Implement the call() method
Function.prototype.myCall = function () { var ctx = arguments[0] || window; ctx.fn = this; var args = []; for (var i = 1; i < arguments.length; i++) { args.push(arguments[i]) } var result = ctx.fn(... args); delete ctx.fn; return result; }Copy the code
Implement the apply() method
Function.prototype.myApply = function () { var ctx = arguments[0] || window; ctx.fn = this; if (! arguments[1]) { var result = ctx.fn(); delete ctx.fn; return result; } var result = ctx.fn(... arguments[1]); delete ctx.fn; return result; }Copy the code
39, stabilization,
function debounce(handle, delay) {
var timer = null;
return function () {
var _self = this,
_args = arguments;
clearTimeout(timer);
timer = setTimeout(function () {
handle.apply(_self, _args)
}, delay)
}
}
Copy the code
40, throttling
function throttle(handler, wait) { var lastTime = 0; return function (e) { var nowTime = new Date().getTime(); if (nowTime - lastTime > wait) { handler.apply(this, arguments); lastTime = nowTime; }}}Copy the code
RequestAnimFrame compatibility method
window.requestAnimFrame = (function () { return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function (callback) { window.setTimeout(callback, 1000 / 60); }; }) ();Copy the code
CancelAnimFrame compatibility method
window.cancelAnimFrame = (function () { return window.cancelAnimationFrame || window.webkitCancelAnimationFrame || window.mozCancelAnimationFrame || function (id) { window.clearTimeout(id); }; }) ();Copy the code
43, JSONP underlying methods
function jsonp(url, callback) { var oscript = document.createElement('script'); If (oscript. ReadyState) {/ / Internet explorer and the following version oscript onreadystatechange = function () {if (oscript. The readyState = = = 'complete' || oscript.readyState === 'loaded') { callback(); } } } else { oscript.onload = function () { callback() }; } oscript.src = url; document.body.appendChild(oscript); }Copy the code
44, Get url parameter (2)
function getUrlParam(sUrl, sKey) { var result = {}; sUrl.replace(/(\w+)=(\w+)(? =[&|#])/g, function (ele, key, val) { if (! result[key]) { result[key] = val; } else { var temp = result[key]; result[key] = [].concat(temp, val); } }) if (! sKey) { return result; } else { return result[sKey] || ''; }}Copy the code
Formatting time
function formatDate(t, str) { var obj = { yyyy: t.getFullYear(), yy: ("" + t.getFullYear()).slice(-2), M: t.getMonth() + 1, MM: ("0" + (t.getMonth() + 1)).slice(-2), d: t.getDate(), dd: ("0" + t.getDate()).slice(-2), H: t.getHours(), HH: ("0" + t.getHours()).slice(-2), h: t.getHours() % 12, hh: ("0" + t.getHours() % 12).slice(-2), m: t.getMinutes(), mm: ("0" + t.getMinutes()).slice(-2), s: t.getSeconds(), ss: ("0" + t.getSeconds()).slice(-2), w: [' day ', 'a', '2', '3', '4', '5', '6'] [t.g etDay ()]}. return str.replace(/([a-z]+)/ig, function ($1) { return obj[$1] }); }Copy the code
46. Verify the mailbox regular expression
function isAvailableEmail(sEmail) {
var reg = /^([\w+.])+@\w+([.]\w+)+$/
return reg.test(sEmail)
}
Copy the code
47. The function Corrification
// Convert a function that takes multiple arguments to a function that takes a single argument (the first argument of the original function), Function curryIt(fn) {var length = fn.length, args = []; var length = fn.length, args = []; var result = function (arg) { args.push(arg); length--; if (length <= 0) { return fn.apply(this, args); } else { return result; } } return result; }Copy the code
Add large numbers
Function sumBigNumber(a, b) {var temp = 0; // the result of the bitwise increment and the carry a = a.split(" "); b = b.split(''); While (a. ength | | b.l ength | | temp) {/ / ~ ~ bitwise not 1. Type conversion, converted to digital 2. ~ ~ undefined temp + = = = 0 ~ ~ Amy polumbo op () + ~ ~ p. op (); res = (temp % 10) + res; temp = temp > 9; } return res.replace(/^0+/, ''); }Copy the code
49. Singleton mode
function getSingle(func) {
var result;
return function () {
if (!result) {
result = new func(arguments);
}
return result;
}
}
Copy the code
50, load js | | CSS | | style
const loadRes = function(name, type, Fn) {/ / load js | | CSS | | style let ref if (type = = = 'javascript') {/ / external js ref = document. The createElement method (' script ') ref.setAttribute('type', 'text/JavaScript') ref.setAttribute('src', Name)} else if (type === 'CSS ') {// external CSS ref = document.createElement('link') ref. SetAttribute ('rel', 'stylesheet') ref.setAttribute('type', 'text/css') ref.setAttribute('href', name) } else if (type === 'style') { // style ref = document.createElement('style') ref.innerhtml = name } if (typeof ref ! Undefined = = ' ') {document. GetElementsByTagName (' head ') [0]. The appendChild (ref) ref. Onload = function () {/ / loaded typeof execution fn === 'function' && fn() } } }Copy the code
51. Get URL parameters (3)
Const getUrlParam = function (name) {/ / get the url parameter let reg = new RegExp (' (^ | &?) ' + name + '=([^&]*)(&|$)', 'i') let r = window.location.href.substr(1).match(reg) if (r ! = null) { return decodeURI(r[2]) } return undefined }Copy the code
52. Local storage
Const store = {// local store set: Function (name, value, day) {/ / set the let d = new Date () let time = 0 day = (typeof (day) = = = 'undefined' | |! day) ? 1: Localstorage.setitem (name, json.stringify ({data: = 0)) localstorage.setitem (name, json.stringify ({data: = 0) Let data = localstorage.getitem (name) if (! Parse (data) if (new Date().getTime() > obj.time) {// Expire localStorage.removeItem(name) return null } else { return obj.data } }, clear: Localstorage.removeitem (name)} else {// Clear all localstorage.clear ()} }}Copy the code
53, Cookie operation [set, get, del]
Const cookie = {// cookie set, get, del] set: function(name, value, day) { let oDate = new Date() oDate.setDate(oDate.getDate() + (day || 30)) document.cookie = name + '=' + value + '; expires=' + oDate + "; path=/;" }, get: function(name) { let str = document.cookie let arr = str.split('; ') for (let i = 0; i < arr.length; i++) { let newArr = arr[i].split('=') if (newArr[0] === name) { return newArr[1] } } }, del: function(name) { this.set(name, '', -1) } }Copy the code
54, Js get element style [support inline]
const getRealStyle = function(obj, Var realStyle = null if (obj.currentStyle) {realStyle = obj.currentStyle[styleName]} else if (window.getComputedStyle) { realStyle = window.getComputedStyle(obj, null)[styleName] } return realStyle }Copy the code
Time formatting
Const formatDate = function(FMT, date) {const formatDate [' YYYY-MM-DD hh: MM :ss', time] if (typeof date! == 'object') { date = ! date ? New Date () : the new Date (Date) = {} var o 'M +' : the Date getMonth () + 1, / / 'd + : in the Date, getDate (), / / day' h + ': Date. GetHours (), / / hours' m + ': the date. The getMinutes (), / /' s + ': the date. The getSeconds (), / / SEC' q + ': Math. Floor ((date, getMonth () + 3) / 3), / / quarter 'S' : Date.getmilliseconds () // milliseconds} if (/(y+)/.test(FMT)) {FMT = FMT. Replace (RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length)) } for (var k in o) { if (new RegExp('(' + k + ')').test(fmt)) { fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length))) } } return fmt }Copy the code
56. Native Ajax Operations (2)
Const ajax = function(conf) {// let url = conf.url, data = conf.data, senData = [], // Encapsulate data async = conf.async! == undefined ? conf.async : True, / / true for asynchronous request type = conf. Type | | 'get', / / the default request way get dataType = conf., dataType | | 'json, contenType = conf.contenType || 'application/x-www-form-urlencoded', success = conf.success, error = conf.error, IsForm = conf. IsForm | | false, / / whether the formdata header = conf. Header | | {}, If (data == null) {senData = ""} else if (typeof data === 'object' &&! IsForm) {// If data is an object, For (var k in data) {sendata.push (encodeURIComponent(k) + '=' + encodeURIComponent(data[k]))} senData = Sendata.join ('&')} else {senData = data} try {XHR = new ActiveXObject('microsoft.xmlhttp') // IE kernel series browser} Catch (e1) {try {XHR = new XMLHttpRequest() // Non-IE kernel browser} catch (e2) {if (error! = null) {error(' Ajax requests are not supported ')}}}; xhr.open(type, type ! == 'get' ? url : url + '? ' + senData, async) if (type ! == 'get' && ! isForm) { xhr.setRequestHeader('content-type', contenType) } for (var h in header) { xhr.setRequestHeader(h, header[h]) } xhr.send(type ! == 'get' ? senData : null) xhr.onreadystatechange = function() { if (xhr.readyState === 4) { if (xhr.status >= 200 && xhr.status < 300) { if (dataType === 'json' && success ! = null) { let res = '' try { res = eval('(' + xhr.responseText + ')') } catch (e) { console.log(e) } success(res) // Convert json string to JS object}; } else { if (error ! = null) {error(' Communication failed! ' + xhr.status) } } } } }Copy the code
57. Fetch request encapsulation
Const fetch = function(url, setting) {const fetch = function(url, setting) { (setting method | | 'GET'). The toUpperCase (), / / way of request headers: setting. The headers | | {}, / / request head set credentials: Setting. The credentials | | true, / / set the cookie is sent with the body: setting. The body | | {}, mode: Setting. The mode | | 'no - cors, / / you can set the cors, no - cors, same - origin redirect: setting.redirect || 'follow', // follow, error, manual cache: Setting the cache | | 'default' / / set the cache mode (the default, reload, No - cache)} let dataType = setting. The dataType | | 'json / / analytic way let data = setting. The data | |' / / parameter let paramsFormat = Function (obj) {var STR = "for (var I in obj) {STR += '${I}=${obj[I]}&'} return str.split(").slice(0, -1).join('') } if (opts.method === 'GET') { url = url + (data ? `? ${paramsFormat(data)}` : '') } else { setting.body = data || {} } return new Promise((resolve, reject) => { fetch(url, opts).then(async res => { let data = dataType === 'text' ? await res.text() : dataType === 'blob' ? await res.blob() : await res.json() resolve(data) }).catch(e => { reject(e) }) }) }Copy the code
58, device judgment: Android, ios, Web
Const isDevice = function () {/ / it is android or ios or web var ua. = the navigator userAgent. ToLowerCase () the if (ua.match(/iPhone\sOS/i) === 'iphone os' || ua.match(/iPad/i) === 'ipad') { // ios return 'iOS' } if (ua.match(/Android/i) === 'android') { return 'Android' } return 'Web' }Copy the code
Judge whether it is wechat
Const isWx = function () {/ / determine whether for WeChat var ua = window. The navigator. UserAgent. ToLowerCase () if (ua) match (/ MicroMessenger/I) === 'micromessenger') { return true } return false }Copy the code
60. Text copy function
Const copyTxt = function(text, fn) {if (typeof document. ExecCommand! == 'function') {console.log( Return} var dom = document.createElement('textarea') dom.value = text dom.setAttribute('style', 'display: block; width: 1px; height: 1px; ') document.body.appendChild(dom) dom.select() var result = document.execCommand('copy') document.body.removeChild(dom) If (result) {console.log(' copy succeeded ') Typeof fn === 'function' && fn() return} if (Typeof document.createrange! == 'function') {console.log( Var range = document.createrange () var div = document.createElement('div') div.innerhtml = text div.setAttribute('style', 'height: 1px; fontSize: 1px; overflow: hidden; ') document.body.appendChild(div) range.selectNode(div) var selection = window.getSelection() console.log(selection) if (selection.rangeCount > 0) { selection.removeAllRanges() } selection.addRange(range) document.execCommand('copy') typeof Fn === 'function' && fn() console.log(' copy succeeded ')}Copy the code
Check if it is an array
Const isArray = function (arr) {/ / judge whether return an Array Object. The prototype. The toString. Call (arr) = = = '[Object Array]'}Copy the code
62, Check whether two arrays are equal
Const arrayEqual = function(arr1, arr2) {if (arr1 === arr2) return true; if (arr1.length ! = arr2.length) return false; for (let i = 0; i < arr1.length; ++i) { if (arr1[i] ! == arr2[i]) return false; } return true; }Copy the code
Time and timestamp conversion
Const stamp = {const stamp = const stamp; const stamp = {const stamp = const stamp; const stamp = {const stamp = const stamp; new Date(time) : new Date() return Math.round(date.getTime() / 1000) }, timeToStr: Function (time, FMT) {/ / 10 timestamp time return new Date (time * 1000). The pattern (FMT | | '- dd yyyy - MM)}}Copy the code
64, commonly used regular verification
Const checkStr = function(STR, type) {switch (type) {case 'phone': / / cell phone number return / ^ 1 [3 4 5 6 7 | | | | | | 8, 9] [0-9] {9} $/. The test (STR) case 'tel: / / machine return / ^ (0 \ d {2, 3} - \ d {7, 8}) (\ d {1, 4})? $/. The test case (STR) "card" : return / / / id (^ \ d {15} $) | | (^ \ d {and} $) (^ \ d {and} (\ d | | X) X $) /. The test case 'PWD (STR) : Return /^[a-za-z]\w{5,17}$/. Test (STR) case 'postal': // Return /[1-9]\d{5}(? ! The (STR) \ d)/case 'QQ' : / / QQ number return / ^ (1-9] [0-9] {4, 9} $/. The test (STR) case 'email: / / email return / ^ [-] \ w + (. [/ w] +) * @ [-] \ w + (. [/ w] +) + $/. The test (STR) case 'money: / / amount (point 2) return / ^ \ d * (? : d \} {0, 2)? The (STR) $/ case 'URL: / / URL return / | | FTP HTTPS (HTTP) : / / / \ w - _ + (. - _] [\ w +) + ([\ w -, @? ^ = % & : / ~ + #] * [\ w - @? ^ = # % & / ~ +])? /.test(str) case 'IP': // IP return /((? : (? :25[0-5]|2[0-4]\d|[01]? \d? \d)\.) {3} (? :25[0-5]|2[0-4]\d|[01]? \d? \ d))/test (STR) case 'date: / / date/time return / ^ (\ d {4}) - (\ d {2}) - (\ d {2}) ((\ d {2})? ::\d{2}|:(\d{2}):(\d{2}))$/.test(str) || /^(\d{4})-(\d{2})-(\d{2})$/.test(str) case 'number': / / digital return / ^ [0-9] $/. The test (STR) case 'English' : / return/English / ^ [a zA - Z] + $/. The test (STR) case 'Chinese' : / / Chinese return / ^ [\ u4E00 - \ u9FA5] + $/. The test (STR) case 'lower' : / / lowercase return / ^ [a-z] + $/. The test (STR) case 'upper' : Capital return / / / ^ [a-z] + $/. The test case 'HTML' (STR) : / / HTML tags return / < (" ^ "] * '|' [^ '] * '| [^' ">]) * > /. The test (STR) default: return true } }Copy the code
65. Check whether it is a PC
Const isPC = function() {// let userAgentInfo = navigator. UserAgent let Agents = ['Android', 'iPhone', 'SymbianOS', 'Windows Phone', 'iPad', 'iPod'] let flag = true for (let v = 0; v < Agents.length; v++) { if (userAgentInfo.indexOf(Agents[v]) > 0) { flag = false break } } return flag }Copy the code
66. Remove string Spaces
Const trim = function (STR, type) {/ / remove Spaces, type: 1 - space in front of all blank Spaces before and after 2-3-4 - after space type = type | | 1 switch (type) {case 1: return str.replace(/\s+/g, '') case 2: return str.replace(/(^\s*)|(\s*$)/g, '') case 3: return str.replace(/(^\s*)/g, '') case 4: return str.replace(/(\s*$)/g, '') default: return str } }Copy the code
67, string case conversion
Const changeCase = function(STR, type) { 1:2: capitalize the first letter home mother lowercase 3: case conversion 4: all upper case 5: all lowercase type = type | | 4 switch (type) {case 1: return str.replace(/\b\w+\b/g, function(word) { return word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase() }) case 2: return str.replace(/\b\w+\b/g, function(word) { return word.substring(0, 1).toLowerCase() + word.substring(1).toUpperCase() }) case 3: return str.split('').map(function(word) { if (/[a-z]/.test(word)) { return word.toUpperCase() } else { return word.toLowerCase() } }).join('') case 4: return str.toUpperCase() case 5: return str.toLowerCase() default: return str } }Copy the code
68. Filter HTML code
Const filterTag = function(STR) {// Filter HTML code (convert <>) STR = str.replace(/&/ig, '&') STR = str.replace(/</ig, '<') str = str.replace(/>/ig, '>') str = str.replace(' ', ' ') return str }Copy the code
Generate random number range
const random = function(min, If (arguments.length === 2) {return math.floor (min + math.random () * ((Max + 1) -min))} else {return math.floor (min + math.random () * (Max + 1) -min))} else { return null } }Copy the code
70. Convert Arabic numerals to Uppercase Chinese numerals
Const numberToChinese = function(num) {let AA = new Array(' 0 ', '1 ',' 2 ', '3 ',' 4 ', '5 ',' 6 ', '7 ', '8', '9', '10') let BB = new Array (', '10', 'best', '$',' m ', '$',' points', ') let a = (' + num.) replace (/ (* ^ 0)/g, '').split('.') let k = 0 let re = '' for (let i = a[0].length - 1; i >= 0; i--) { switch (k) { case 0: re = BB[7] + re break case 4: if (! new RegExp('0{4}//d{' + (a[0].length - i - 1) + '}$').test(a[0])) { re = BB[4] + re } break case 8: re = BB[5] + re BB[7] = BB[5] k = 0 break } if (k % 4 === 2 && a[0].charAt(i + 2) ! == 0 && a[0].charAt(i + 1) === 0) { re = AA[0] + re } if (a[0].charAt(i) ! {re = = = 0) AA [a [0]. The charAt (I)] + BB + re} % 4 [k] k++} the if (a. ength > 1) {/ / plus the decimal part (if there is a decimal part) re + = BB [6] for (let I = 0; i < a[1].length; I++) {re + = AA [a [1]. The charAt (I)]}} the if (re = = = 'ten') = 'ten'} of {re the if (re. Match (a / / ^) && re. The length = = = 3) {re = Re.replace (' one ', '')} return re}Copy the code
Native DOM manipulation
const dom = { $: function(selector) { let type = selector.substring(0, 1) if (type === '#') { if (document.querySelecotor) return document.querySelector(selector) return document.getElementById(selector.substring(1)) } else if (type === '.') { if (document.querySelecotorAll) return document.querySelectorAll(selector) return document.getElementsByClassName(selector.substring(1)) } else { return document['querySelectorAll' ? 'querySelectorAll' : 'getElementsByTagName'](selector) } }, hasClass: Function (ele, name) {/ * test class name * / return ele. ClassName. Match (new RegExp (' (\ s | ^) '+ name +' (\ s | $)))}, addClass: Function (ele, name) {/* Add class name */ if (! this.hasClass(ele, name)) ele.className += ' ' + name }, removeClass: Function (ele, name) {/* Delete class name */ (this.hasclass (ele, name)) { let reg = new RegExp('(\s|^)' + name + '(\s|$)') ele.className = ele.className.replace(reg, '') } }, replaceClass: Function (ele, newName, oldName) {/* Replace the name of the class */ this.removeClass(ele, oldName) this.addClass(ele, newName)}, siblings: Function (ele) {/* Get siblings */ console.log(ele.parentNode) let chid = ele.parentNode.children, eleMatch = [] for (let i = 0, len = chid.length; i < len; i++) { if (chid[i] ! == ele) { eleMatch.push(chid[i]) } } return eleMatch }, getByStyle: function(obj, Name) {/* getComputedStyle */ if (obj.currentStyle) {return obj.currentStyle[name]} else {return getComputedStyle(obj, false)[name] } }, domToStirng: Div = document.createElement('div') div. AppendChild (htmlDOM) return div.innerhtml }, stringToDom: Function (htmlString) {/* String to DOM */ var div = document.createElement('div') div.innerhtml = htmlString return div.children[0] } }Copy the code
72. Judge the image loading is complete
Const imgLoadAll = function(arr, callback) {let arrImg = [] for (let I = 0; i < arr.length; i++) { let img = new Image() img.src = arr[i] img.onload = function() { arrImg.push(this) if (arrImg.length == arr.length) { callback && callback() } } } }Copy the code
73. Audio loading is complete
const loadAudio = function(src, Callback) {var audio = new audio (SRC) audio. Onloadedmetadata = callback audio. SRC = SRC}Copy the code
74. Insert character at cursor position
const insertAtCursor = function(dom, Val) {/ / insertion cursor characters if (document. Selection) {dom. Focus () let sel. = the document selection. CreateRange (sel). The text = val sel.select() } else if (dom.selectionStart || dom.selectionStart == '0') { let startPos = dom.selectionStart let endPos = dom.selectionEnd let restoreTop = dom.scrollTop dom.value = dom.value.substring(0, startPos) + val + dom.value.substring(endPos, dom.value.length) if (restoreTop > 0) { dom.scrollTop = restoreTop } dom.focus() dom.selectionStart = startPos + val.length dom.selectionEnd = startPos + val.length } else { dom.value += val dom.focus() } }Copy the code
75, Image address to base64
Const getBase64 = function(img) {// getBase64(url). Then (function(base64){},function(err){}); Let getBase64Image = function(img, width, height) { Let canvas = document.createElement("canvas"); canvas.width = width ? width : img.width; canvas.height = height ? height : img.height; let ctx = canvas.getContext("2d"); ctx.drawImage(img, 0, 0, canvas.width, canvas.height); let dataURL = canvas.toDataURL(); return dataURL; } let image = new Image(); image.crossOrigin = ''; image.src = img; let deferred = $.Deferred(); if (img) { image.onload = function() { deferred.resolve(getBase64Image(image)); } return deferred.promise(); }}Copy the code
Base64 image download function
const downloadFile = function(base64, FileName) {// base64ToBlob = function(code) {let parts = code.split('; base64,'); let contentType = parts[0].split(':')[1]; let raw = window.atob(parts[1]); let rawLength = raw.length; let uInt8Array = new Uint8Array(rawLength); for (let i = 0; i < rawLength; ++i) { uInt8Array[i] = raw.charCodeAt(i); } return new Blob([uInt8Array], { type: contentType }); }; let aLink = document.createElement('a'); let blob = base64ToBlob(base64); //new Blob([content]); let evt = document.createEvent("HTMLEvents"); evt.initEvent("click", true, true); //initEvent (FF, FF, FF, FF); //initEvent (FF, FF, FF); aLink.href = URL.createObjectURL(blob); aLink.click(); }Copy the code
77. Whether the browser supports webP images
Const isSupportWebP = function() {return!! [].map && document.createElement('canvas').toDataURL('image/webp').indexOf('data:image/webp') == 0; }Copy the code
78, URL parameter to object
Const parseQueryString = function(url) {const parseQueryString = function(url) { url ? window.location.href : url; if (url.indexOf('? ') === -1) { return {}; } let search = url[0] === '? '? url.substr(1) : url.substring(url.lastIndexOf('? ') + 1); if (search === '') { return {}; } search = search.split('&'); let query = {}; for (let i = 0; i < search.length; i++) { let pair = search[i].split('='); query[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || ''); } return query; }Copy the code
79, Object serialization
Const stringfyQueryString = function(obj) {// If (! obj) return ''; let pairs = []; for (let key in obj) { let value = obj[key]; if (value instanceof Array) { for (let i = 0; i < value.length; ++i) { pairs.push(encodeURIComponent(key + '[' + i + ']') + '=' + encodeURIComponent(value[i])); } continue; } pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key])); } return pairs.join('&'); }Copy the code
H5 soft keyboard retract, bounce back
Const h5Resize = function(downCb, upCb) {// innerHeight changes when the software keyboard is up. Var clientHeight = window.innerheight; downCb = typeof downCb === 'function' ? downCb : function() {} upCb = typeof upCb === 'function' ? upCb : function() {} window.addEventListener('resize', () => { var height = window.innerHeight; if (height === clientHeight) { downCb(); } if (height < clientHeight) { upCb(); }}); }Copy the code
Function shake proof
const debounce = function(func, wait, Immediate) {func function, number of milliseconds to wait for execution,immediate true,false,immediate Then the effect of the function can continue without raising the event for n seconds. return function() { let context = this; let args = arguments; if (timeout) clearTimeout(timeout); if (immediate) { var callNow = ! timeout; timeout = setTimeout(() => { timeout = null; }, wait) if (callNow) func.apply(context, args) } else { timeout = setTimeout(function() { func.apply(context, args) }, wait); }}}Copy the code
Function throttling
Const throttle = function(func, wait,type) {const throttle = function(func, wait,type) { If (type===1){let previous = 0; }else if(type===2){ let timeout; } return function() { let context = this; let args = arguments; if(type===1){ let now = Date.now(); if (now - previous > wait) { func.apply(context, args); previous = now; } }else if(type===2){ if (! timeout) { timeout = setTimeout(() => { timeout = null; func.apply(context, args) }, wait) } } }Copy the code