1. Enter a value and return its data type**function type(para) { return Object.prototype.toString.call(para) } 2. Array deduplicationfunction 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; } 3. String deduplicationString.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 consecutive strings function uniq(str) { return str.replace(/(\w)\1+/g, '$1') } 4. Deep copy and shallow copy//Deep clone (deep clone 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.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; } // Deep and shallow cloning is for reference value function deepClone(target) { if (typeof (target) !== 'object') { return target; } var result; if (Object.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; } // Unable to copy function var o1 = jsON.parse(jsON.stringify(obj1)); 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; } 6. Inheritance of the Holy Grail Patternfunction 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 = Origin.prototype; } 7. Find the first letter that appears only once in a stringString.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; } } } 8. Find the nth level parent element of an elementfunction parents(ele, n) { while (ele && n) { ele = ele.parentElement ? ele.parentElement : ele.parentNode; n--; } return ele; } 9. Return the nth sibling node of an elementfunction 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; } 10. Encapsulate mychildren to solve browser compatibility issuesfunction 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; } 11. Determine whether an element has child elementsfunction 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; } 12. I insert an element after another elementElement.prototype.insertAfter = function (target, elen) { var nextElen = elen.nextElenmentSibling; if (nextElen == null) { this.appendChild(target); } else { this.insertBefore(target, nextElen); } } 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 + "year" + month + "month" + day + "day" + hour + "hour" + minute + "minute" + second + "second" } 14. Get the scroll distance of the scroll barfunction 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 } } } 15. Get the size of the viewportfunction getViewportOffset() { if (window.innerWidth) { return { w: window.innerWidth, h: window.innerHeight } } else { // ie8 and below if (document.compatMode === "BackCompat") { // Quirks mode return { w: document.body.clientWidth, h: document.body.clientHeight } } else { // Standard mode return { w: document.documentElement.clientWidth, h: document.documentElement.clientHeight } } } } 16. Get any attribute of any elementfunction getStyle(elem, prop) { return window.getComputedStyle ? window.getComputedStyle(elem, null)[prop] : elem.currentStyle[prop] } 17. Compatible code for binding eventsfunction addEvent(elem, type, handle) { if (elem.addEventListener) { //non-IE and non-IE9 elem.addEventListener(type, handle, false); } else if (elem.attachEvent) { //ie6 to ie8 elem.attachEvent('on' + type, function () { handle.call(elem); }) } else { elem['on' + type] = handle; } } 18. Unbinding Eventfunction removeEvent(elem, type, handle) { if (elem.removeEventListener) { //non-IE and non-IE9 elem.removeEventListener(type, handle, false); } else if (elem.detachEvent) { //ie6 to ie8 elem.detachEvent('on' + type, handle); } else { elem['on' + type] = null; } } 19. Cancel the compatible code of bubblingfunction stopBubble(e) { if (e && e.stopPropagation) { e.stopPropagation(); } else { window.event.cancelBubble = true; } } 20. Check if a string is a palindromefunction 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; } 21. Check if a string is a palindromefunction isPalindrome(str) { str = str.replace(/\W/g, '').toLowerCase(); console.log(str) return (str == str.split('').reverse().join('')) } 22. Compatible with getElementsByClassName methodElement.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; } 23. Motion Functionfunction 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) } 24. Elastic exercisefunction 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); } 25. Encapsulate your own forEach methodArray.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) } } 26. Encapsulate your own filter methodArray.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; } 27. Array map methodArray.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; } 28. Array every methodArray.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; } 29. Array reduce methodArray.prototype.myReduce = function (func, initialValue) { var len = this.length, nextValue, i; if (!initialValue) { // No second parameter passed nextValue = this[0]; i = 1; } else { // Pass the second parameter nextValue = initialValue; i = 0; } for (; i < len; i++) { nextValue = func(nextValue, this[i], i, this); } return nextValue; } 30. Get the parameters in the URLfunction 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; } 31. Array Sorting// Quick sort [left] + min + [right] function quickArr(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]); } } // Recursion return quickArr(left).concat([p], quickArr(right)); } // Bubble 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; } 32. Traversing the Dom tree Given a function traverse(element, callback) { callback(element); var list = element.children; for (var i = 0; i < list.length; i++) { traverse(list[i], callback); } } 33. Native js encapsulation ajaxfunction 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); } } 34. Load script asynchronouslyfunction loadScript(url, callback) { var oscript = document.createElement('script'); if (oscript.readyState) { // ie8 and below oscript.onreadystatechange = function () { if (oscript.readyState === 'complete' || oscript.readyState === 'loaded') { callback(); } } } else { oscript.onload = function () { callback() }; } oscript.src = url; document.body.appendChild(oscript); } 35. Cookie managementvar 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; } } 36. Implement the bind() methodFunction.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; } 37. Implement the call() methodFunction.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; } 38. Implement the apply() methodFunction.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; } 39. Anti-shakefunction debounce(handle, delay) { var timer = null; return function () { var _self = this, _args = arguments; clearTimeout(timer); timer = setTimeout(function () { handle.apply(_self, _args) }, delay) } } 40. Throttlingfunction throttle(handler, wait) { var lastTime = 0; return function (e) { var nowTime = new Date().getTime(); if (nowTime - lastTime > wait) { handler.apply(this, arguments); lastTime = nowTime; } } } 41. requestAnimFrame compatibility methodwindow.requestAnimFrame = (function () { return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function (callback) { window.setTimeout(callback, 1000 / 60); }; })(); 42. cancelAnimFrame compatibility methodwindow.cancelAnimFrame = (function () { return window.cancelAnimationFrame || window.webkitCancelAnimationFrame || window.mozCancelAnimationFrame || function (id) { window.clearTimeout(id); }; })(); 43. jsonp underlying methodfunction jsonp(url, callback) { var oscript = document.createElement('script'); if (oscript.readyState) { // ie8 and below oscript.onreadystatechange = function () { if (oscript.readyState === 'complete' || oscript.readyState === 'loaded') { callback(); } } } else { oscript.onload = function () { callback() }; } oscript.src = url; document.body.appendChild(oscript); } 44. Get the parameters on the URLfunction 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] || ''; } } 45. Format timefunction 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: ['日', 'MON', 'TU', 'WED', 'THUR', 'FRI', 'SAT'][t.getDay()] }; return str.replace(/([az]+)/ig, function ($1) { return obj[$1] }); } 46. Regular expression for verifying email addressesfunction isAvailableEmail(sEmail) { var reg = /^([\w+\.])+@\w+([.]\w+)+$/ return reg.test(sEmail) } 47. Function CurryingIt is a technique to transform a function that accepts multiple parameters into a function that accepts a single parameter (the first parameter of the original function) and returns a new function that accepts the remaining parameters and returns the result. function curryIt(fn) { 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; } 48. Adding large numbersfunction sumBigNumber(a, b) { var res = '', // result temp = 0; // bitwise addition result and carry a = a.split(''); b = b.split(''); while (a.length || b.length || temp) { //~~Bitwise NOT 1. Type conversion, converted to number 2.~~undefined==0 temp += ~~a.pop() + ~~b.pop(); res = (temp % 10) + res; temp = temp > 9; } return res.replace(/^0+/, ''); } 49. Singleton Patternfunction getSingle(func) { var result; return function () { if (!result) { result = new func(arguments); } return result; } } This is the end of this article about the commonly used front-end JavaScript method encapsulation. For more relevant front-end JavaScript method encapsulation content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future! You may also be interested in:
|
<<: Detailed steps for configuring mysql8.0.20 with binlog2sql and simple backup and recovery
>>: How to add sudo permissions to a user in Linux environment
Preface: MySQL master-slave architecture should b...
You may remember that in the past articles we hav...
MySQL multi-table query Add a worksheet -- User t...
1. Download MySQL database and install and config...
Operation effectCode Implementation html <div ...
Preface: The previous articles introduced the usa...
As of now, the latest version of CentOS is CentOS...
Disabling and enabling MySQL foreign key constrai...
The implementation principle of Vue2.0/3.0 two-wa...
The reuse of code in vue provides us with mixnis....
When MySQL performs DDL operations such as alter ...
Native js encapsulated seamless carousel plug-in,...
This article is an integrated article on how to c...
When we write CSS, we sometimes forget about the ...
If you want to become a Linux master, then master...