最近整理了一下工作中经常用到的一些js方法供大家使用。新手必看,大神可以直接绕过,哈哈哈!!!
// 姓名 或 手机号 中间替换成 * 或 **** var reg = /d+/g // 提取所有数字 function encryption(str, i){ switch( i ){ // case 1 : return str.replace(str, str.substr(0,3) + "****" + str.substr(7,4) ); case 1 : return str.replace(/(d{3})d{4}(d{4})/, '$1***$2'); break; case 2 : return str.replace(str, str.substr(0,1) + "*" + str.substr(2,str.length) ); break; case 3 : return str.replace(str, str.substr(0,4) + "-" + str.substr(4,2) + "-" + str.substr(6,2) ); break; case 4 : return str.replace(str, str.substr(-4,str.length)); break; } } console.log( encryption('13454677453', 1), encryption('周杰伦', 2), encryption('20161206', 3), encryption('20161206', 4) ); //将所有首字母转换成大写 name = 'aaa bbb ccc'; uw = name.replace(/w+/g, function(word){ return word.substring(0,1).toUpperCase() + word.substring(1); }); console.log(uw); //数组去重 var unique = function(arr){ var obj = {}; var newArr = []; arr.forEach(function(x){ if(!obj[x]){ //如果对象中没有该元素对应的属性 obj[x] = true; newArr.push(x); } }); return newArr; } console.log( unique(['12','23','12','你好','12312','32','你好']) ) //冒泡排序 l = [1, 98, 34, 23, 8, 32]; function bubbleSort(arr) { newarr = arr.slice(); if (newarr.length <= 2) return newarr; for (var i = 0; i < newarr.length - 1; i++) { for (var j = 0; j < newarr.length - i - 1; j++) { if (newarr[j] > newarr[j + 1]) { newarr[j] = [newarr[j + 1], newarr[j + 1] = newarr[j]][0]; } } } return newarr; } console.log( bubbleSort(l) ); // 用 filter 过滤数组 var data2 = ['12','322','1221','122','12']; function dataFilter(nav){ return nav !== '12'; } var newFilter = data2.filter(dataFilter) console.log(newFilter); //线性搜索(入门HelloWorld) //A为数组,x为要搜索的值 function linearSearch(A, x) { for (var i = 0; i < A.length; i++) { if (A[i] == x) { return i; } } return -1; } console.log('线性搜索 ' + linearSearch( data2, '1221' )); //数组中指定元素提到最前边 ['',''] || [{},{}] 都可以 var datas = [ {nav: "3.0793", navDate: "20161203", profitOf10K: "1.1419"}, {nav: "3.0792", navDate: "20161202", profitOf10K: "1.1419"}, {nav: "3.7797", navDate: "20161201", profitOf10K: "1.0332"}, {nav: "3.0798", navDate: "20161204", profitOf10K: "1.1419"} ]; function beforeSort(arr, key){ var a; for (var i = 0; i < arr.length; i++) { if ( typeof arr[0] === 'object' ){ b = arr[i].nav; } else { b = arr[i]; } if ( b === key ) { a = arr[i]; arr.splice(i, 1); break; } } arr.unshift(a); return arr; } console.log( beforeSort(['1','2','3'], '3') ); //forEach遍历输出到页面 var newData = beforeSort(datas, '3.7797'); var tabs = document.querySelector('#tabs'); newData.forEach(function (e){ tabs.innerHTML += '<tr><td>' + e.nav + '</td><td>' + encryption(e.navDate,3) + '</td></tr>'; });// 将字符串分割,只留一个空格 var str = '123456789'; var space = 'hello world'; console.log( str ); //split('')将字符串转换成数组 console.log( str.split('').reverse().toString() ); var newSpa = space.split('').join(' ').replace(/s+/g, ' '); console.log(newSpa); //银行卡输入每隔 4 位加一个空格 function binkStyle(str) { return str.replace(/s/g,'').replace(/(d{4})(?=d)/g,"$1 "); } var value= '123231312132132'; console.log( binkStyle(value) ); // 重复输出字符串 String.prototype.repeatify = String.prototype.repeatify || function (times){ var str = ''; while (times > 0){ str += this; times --; } return str; } console.log('1234543!@##'.repeatify(2)); // URL地址加密 var _code = encodeURIComponent('http://www.baidu.com'); console.log(_code, decodeURIComponent(_code)); // 数组去重 Array.prototype.uniq = function () { var arr = []; var flag = true; this.forEach(function(item) { // 排除 NaN (重要!!!) if (item != item) { flag && arr.indexOf(item) === -1 ? arr.push(item) : ' '; flag = false; } else { arr.indexOf(item) === -1 ? arr.push(item) : ' ' } }); return arr; } var _arr = ['12','23','12','你好','12312','32','你好']; var _obj = {}, _arr2 = []; for (var i = 0; i < _arr.length; i ++) { if (!_obj[_arr[i]]) { _obj[_arr[i]] = true; _arr2.push(_arr[i]); } } console.log(_arr2, _obj); // 原生Date扩展 toFormatString( yyyy/yy/yy ) Date.prototype.toFormatString = function (format) { var x = this, y = format; var z = { M: x.getMonth() + 1, d: x.getDate(), h: x.getHours(), m: x.getMinutes(), s: x.getSeconds() }; y = y.replace(/(M+|d+|h+|m+|s+)/g, function(v) { return ((v.length > 1 ? "0" : "") + eval('z.' + v.slice(-1))).slice(-2) }); return y.replace(/(y+)/g, function(v) { return x.getFullYear().toString().slice(-v.length) }); } // (new Date()).toFormatString('yyyy-MM-dd'); // 获取当前指定的前几天的日期 getBeforeDate(n){ let d = new Date(); let year = d.getFullYear(); let mon=d.getMonth()+1; let day=d.getDate(); if(day <= n){ if(mon>1) { mon=mon-1; } else { year = year-1; mon = 12; } } d.setDate(d.getDate()-n); year = d.getFullYear(); mon = d.getMonth()+1; day = d.getDate(); let s = year+'-'+(mon<10?('0'+mon):mon)+'-'+(day<10?('0'+day):day); return s; } //获取当天日期 setToday() { let now = new Date() let cmonth = now.getMonth() + 1 let day = now.getDate() if (cmonth < 10) cmonth = '0' + cmonth if (day < 10) day = '0' + day return now.getFullYear() + '-' + cmonth + '-' + day } // 截取 URL 中的参数 var getParams = function(name) { // 用于筛选参数的正则表达式 var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i'); // 对于当前的 Query String 进行正则匹配,得到结果对象 // 如果 ?前边有#,window.location.search会等于 null // 这个时候 // var r = window.location.href.split('?')[1].match(reg); var r = window.location.search.substr(1).match(reg); // 如果匹配成功,返回对应的参数值 if(r) { return decodeURI(r[2]); } // 如果未成功,返回 null 结束 return null; } function getRequest(name) { var url = location.href.indexOf("?") != -1 && location.href.split('?')[1]; //获取url中"?"符后的字串 var theRequest = {}; var strs = url.split("&"); for(var i = 0; i < strs.length; i ++) { theRequest[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]); } return theRequest[name]; } // 字符串中出现次数最多的 function mostString(str){ var obj1 = {}, num = 0, number = ''; for (var i = 0; i < str.length; i ++){ if (!obj1[str.charAt(i)]){ obj1[str.charAt(i)] = 1; } else { obj1[str.charAt(i)]++ } } for (var i in obj1){ if (obj1[i] > num ){ num = obj1[i]; number = i; } } return ['出现最多的字符:' + number + ' ' + '出现次数:' + num, obj1] } console.log( mostString('abdcadfasfdbadfafdasd;;') ); // 点击 li 时都是冒泡到 li 上 function _find1(node, tagName) { tagName = tagName.toUpperCase(); while (node && node.tagName !== tagName) { node = node.parentNode; } return node; } function _find2(el, selector) { var p = Element.prototype; var f = p.matches || p.webkitMatchesSelector || p.mozMatchesSelector || p.msMatchesSelector || function (s) { return [].indexOf.call(document.querySelectorAll(s), this) !== -1; }; while (el && el instanceof HTMLElement && !f.call(el, selector)) { el = el.parentNode; } return el instanceof HTMLElement ? el : null; } // _find(e.target, 'li') // 汉字拼音排序方法 ['asdas','王'].sort(function(a,b){return b.localeCompare(a)}); // element.addEventListener 和 tap事件封装 var EventUtil = { addHandler: function(element, type, handler){ if (element.addEventListener){ element.addEventListener(type, handler, false); } else if (element.attachEvent){ element.attachEvent("on" + type, handler); } else { element["on" + type] = handler; } }, removeHandler: function(element, type, handler){ if (element.removeEventListener){ element.removeEventListener(type, handler, false); } else if (element.detachEvent){ element.detachEvent("on" + type, handler); } else { element["on" + type] = null; } } }; var test = document.getElementById('test'); // EventUtil.addHandler(test, 'click', function () { // console.log('点击了!'); // }); function _find(el, selector) { var p = Element.prototype; var f = p.matches || p.webkitMatchesSelector || p.mozMatchesSelector || p.msMatchesSelector || function(s) { return [].indexOf.call(document.querySelectorAll(s), this) !== -1; }; while (el && el instanceof HTMLElement && !f.call(el, selector)) { el = el.parentNode; } console.log(el); return el instanceof HTMLElement ? el : null; } HTMLElement.prototype.tap = function (callBack) { var startTime=0, delayTime=200, isMove=false; this.addEventListener("touchstart",function(event){ //记录开始时间 startTime=Date.now(); }); this.addEventListener("touchmove",function(event){ //如果发生了移动就改变isMove的值 isMove=true; }); this.addEventListener("touchend",function(event){ //如果发生了移动就不执行回调 if(isMove) { isMove = false; return; } //如果大于延时时间就不执行回调函数 if(Date.now() - startTime > delayTime) return; callBack(event); }); } test.tap(function (e){ var target = _find(e.target, 'li'); console.log(target.getAttribute('data-test')); }); function once(fn, context) { var result; return function() { if(fn) { result = fn.apply(context || this, arguments); fn = null; } return result; }; } // var canOnlyFireOnce = once(function() { // console.log('Fired!'); // }); // document.getElementById('demo').tap(function (){ // canOnlyFireOnce(); // }); var clickTag = 0, demo = document.getElementById('demo'); demo.tap(function (){ clickTag += 1; if (clickTag == 4) clickTag = 1; switch(clickTag){ case 1: demo.classList.remove('active3'); demo.classList.add('active1'); console.log('状态' + clickTag); break; case 2: demo.classList.remove('active1'); demo.classList.add('active2'); console.log('状态' + clickTag); break; case 3: demo.classList.remove('active2'); demo.classList.add('active3'); console.log('状态' + clickTag); break; } }); 在 input 和 p标签中 粘贴/剪切 文字 <p contenteditable="true" onpaste="myFunction()">尝试在段落中粘贴内容。</p> <input type="text" id="myInput" value="尝试在此处粘贴文本" size="40"> <script> document.getElementById("myInput").addEventListener("paste", myFunction); function myFunction() { alert("你粘贴了文本!"); } </script> <p contenteditable="true" oncut="myFunction()">尝试剪切该文本</p> <input type="text" oncut="myFunction()" value="尝试剪切该文本"> <p id="demo"></p> <script> function myFunction() { document.getElementById("demo").innerHTML = "你剪切了文本!"; } </script> <p oncopy="myFunction()">尝试拷贝文本</p> <img src="w3schools.gif" oncopy="myFunction()"> <input type="text" id="myInput" value="尝试拷贝文本"> <script> document.getElementById("myInput").addEventListener("copy", myFunction); function myFunction() { alert("你拷贝了文本!"); } </script> // 获取 N 天后 或者 N 天前 的日期 function GetDateStr(AddDayCount) { var dd = new Date(); dd.setDate(dd.getDate()+AddDayCount);//获取AddDayCount天后的日期 var y = dd.getFullYear(); var m = (dd.getMonth()+1)<10?"0"+(dd.getMonth()+1):(dd.getMonth()+1);//获取当前月份的日期,不足10补0 var d = dd.getDate()<10?"0"+dd.getDate():dd.getDate();//获取当前几号,不足10补0 return y+"-"+m+"-"+d; } // js操作表格 <table border="1" id="tableList"> <thead><tr><td>haha</td><td>haha</td></tr></thead> <tbody> <tr><td>你好</td><td>haha</td></tr> <tr><td>haha</td><td>haha</td></tr> <tr><td>haha</td><td>haha</td></tr> <tr><td>haha</td><td>haha</td></tr> </tbody> </table> var tr = document.getElementById('tableList').children[1].rows; tr[0].cells[1].style.color = 'red'; console.log(tr.length); // 获取元素各种宽高 function getStyle(obj,attr){ if(obj.currentStyle){ return obj.currentStyle[attr]; } else{ return document.defaultView.getComputedStyle(obj,null)[attr]; } } 网页可见区域宽: document.documentElement.clientWidth; 网页可见区域高: document.documentElement.clientHeight; 网页正文全文宽: document.documentElement.scrollWidth; 网页正文全文高: document.documentElement.scrollHeight; 网页被卷去的高(ff):document.body.scrollTop; 网页被卷去的高(ie): document.documentElement.scrollTop; 网页被卷去的左:document.body.scrollLeft; 网页正文部分上:window.screenTop; 网页正文部分左:window.screenLeft; 某个元素的宽度:obj.offsetWidth; 某个元素的高度:obj.offsetHeight; 某个元素的上边界到body最顶部的距离:obj.offsetTop;(在元素的包含元素不含滚动条的情况下) 某个元素的左边界到body最左边的距离:obj.offsetLeft;(在元素的包含元素不含滚动条的情况下) 返回当前元素的上边界到它的包含元素的上边界的偏移量:obj.offsetTop(在元素的包含元素含滚动条的情况下) 返回当前元素的左边界到它的包含元素的左边界的偏移量:obj.offsetLeft(在元素的包含元素含滚动条的情况下) // Js 数组——filter()、map()、some()、every()、forEach()、indexOf() filter(可以增加内容,也可以过滤数组,只返回符合条件的数组) var a = [{name:'aa',sex:'nan'},{name:'bb',sex:'nan'},{name:'cc',sex:'nv'}] a.filter(function(item){ item.num = '1'; return item.sex == 'nan' }) 返回 [{name: "aa", sex: "nan", num: "1"},{name: "bb", sex: "nan", num: "1"}] map(只能返回一个原有长度的数组) var a = [{name:'aa',sex:'nan'},{name:'bb',sex:'nan'},{name:'cc',sex:'nv'}] a.map(function(item){ returnitem.name.toUpperCase() }) 返回 ["AA", "BB", "CC"] var b = ['qwe','EDff','dddd'] b.map(function(item){ return item == 'qwe' }) [true, false, false] var c = [1,2,3,4,5] c.map(function(item){ return item*2 }) 返回 [2, 4, 6, 8, 10] some(数组中有一个大于10就返回true) var a = [1,2,3,4,56,3,21]; a.some(function(item,index,array){ return item > 10 }) 返回 true every(数组中全部大于10才返回true) var a = [1,2,3,4,56,3,21]; a.every(function(item,index,array){ return item > 10 }) 返回 false indexOf(查询数组中是否有某个字段) var a = [1,2,3,4,56,3,21]; a.indexOf(2) 返回 0 a.indexOf(7) 返回 -1 // 电脑发声 var speechSU = new window.SpeechSynthesisUtterance(); speechSU.text = '你好,世界!'; window.speechSynthesis.speak(speechSU); // 根据身份证号获取年龄 function age(ic){ var myDate = new Date(); var month = myDate.getMonth() + 1; var day = myDate.getDate(); var age = myDate.getFullYear() - ic.substring(6, 10) - 1; if (ic.substring(10, 12) < month || ic.substring(10, 12) == month && ic.substring(12, 14) <= day) { age++; } return age; } function GetAge(identityCard) { var len = (identityCard + "").length; if (len == 0) { return 0; } else { if ((len != 15) && (len != 18))//身份证号码只能为15位或18位其它不合法 { return 0; } } var strBirthday = ""; if (len == 18)//处理18位的身份证号码从号码中得到生日和性别代码 { strBirthday = identityCard.substr(6, 4) + "/" + identityCard.substr(10, 2) + "/" + identityCard.substr(12, 2); } if (len == 15) { strBirthday = "19" + identityCard.substr(6, 2) + "/" + identityCard.substr(8, 2) + "/" + identityCard.substr(10, 2); } //时间字符串里,必须是“/” var birthDate = new Date(strBirthday); var nowDateTime = new Date(); var age = nowDateTime.getFullYear() - birthDate.getFullYear(); //再考虑月、天的因素;.getMonth()获取的是从0开始的,这里进行比较,不需要加1 if (nowDateTime.getMonth() < birthDate.getMonth() || (nowDateTime.getMonth() == birthDate.getMonth() && nowDateTime.getDate() < birthDate.getDate())) { age--; } return age; } /* 根据身份证获取生日 */ function getBirthdate(idNo) { if (!idNo) return ''; var len = idNo.length; var bstr = ''; if (len === 15) { bstr = '19' + idNo.substr(6, 6); } else if (len === 18) { bstr = idNo.substr(6, 8); } return bstr.replace(/^(d{4})(d{2})(d{2})$/, '$1-$2-$3'); } /* 根据身份证获取性别 */ function getSex(idNo) { if (!idNo) return ''; var len = idNo.length; var bstr = ''; if (len === 15) { bstr = idNo.substr(14, 1); } else if (len === 18) { bstr = idNo.substr(16, 1); } if (!bstr) return ''; return parseInt(bstr) % 2 === 0 ? 'F' : 'M'; } 字符串转驼峰写法 function transformStr3(str){ var re=/-(w)/g; return str.replace(re,function ($0,$1){ return $1.toUpperCase(); }); } function transformStr3(str) { var arr = str.split('_'); for(var i=1;i<arr.length;i++){ arr[i] = arr[i].charAt(0).toUpperCase()+arr[i].substring(1); } return arr.join(''); } 驼峰写法转字符串 function toTF(str){ var s = "fooStyleCss"; return str.replace(/([A-Z])/g,"-$1").toLowerCase(); } 布局调试加边框 [].forEach.call(document.querySelectorAll('*'),function(a) { a.style.outline = "1px solid #" + (~~ (Math.random() * (1 << 24))).toString(16) }) 数据类型判断 Object.prototype.toString.call('asdsa') "[object String]" Object.prototype.toString.call({a:'1'}) "[object Object]" Object.prototype.toString.call([1,2,3]) "[object Array]" 对象、数组的深拷贝 function objDeepCopy(source) { var sourceCopy = source instanceof Array ? [] : {}; for (var item in source) { sourceCopy[item] = typeof source[item] === 'object' ? objDeepCopy(source[item]) : source[item]; } return sourceCopy; } 函数节流 function throttle (fn, wait) { let _fn = fn, // 保存需要被延迟的函数引用 timer, flags = true; // 是否首次调用 return function() { let args = arguments, self = this; if (flags) { // 如果是第一次调用不用延迟,直接执行即可 _fn.apply(self, args); flags = false; return flags; } // 如果定时器还在,说明上一次还没执行完,不往下执行 if (timer) return false; timer = setTimeout(function() { // 延迟执行 clearTimeout(timer); // 清空上次的定时器 timer = null; // 销毁变量 _fn.apply(self, args); }, wait); } } window.onscroll = throttle(function() { console.log('滚动'); }, 500); 数组对象去重 //将对象元素转换成字符串以作比较 function obj2key(obj, keys){ var n = keys.length, key = []; while(n--){ key.push(obj[keys[n]]); } return key.join('|'); } //去重操作 function uniqeByKeys(array,keys){ var arr = []; var hash = {}; for (var i = 0, j = array.length; i < j; i++) { var k = obj2key(array[i], keys); if (!(k in hash)) { hash[k] = true; arr .push(array[i]); } } return arr ; } 用法: var array = [ {a:1,b:2,c:3,d:4}, {a:11,b:22,c:333,d:44}, {a:111,b:222,c:333,d:444}, {a:11,b:22,c:33,d:44}, {a:11,b:22,c:33,d:444} ]; var arr = uniqeByKeys(array,['a','b']);
原文链接:https://www.wyqsky.top/blog/index.html#/index/details?id=5b18a1c7c929532f8da490a6