前端常用JS代码
1、设置Cookie
setCookie(参数名, 参数, expiredays)
function setCookie(c_name, value, expiredays) { var exdate = new Date(); var times = exdate.getTime() + parseInt(expiredays * 24 * 60 * 60 * 1000) exdate.setTime(times); document.cookie = c_name + "=" + escape(value) + ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString() + "; path=/") }
2、读取Cookie
getCookie(参数名)
function getCookie(c_name) { if (document.cookie.length > 0) { c_start = document.cookie.indexOf(c_name + "=") if (c_start != -1) { c_start = c_start + c_name.length + 1 c_end = document.cookie.indexOf(";", c_start) if (c_end == -1) c_end = document.cookie.length return unescape(document.cookie.substring(c_start, c_end)) } } return "" }
3、 截取最后一个斜杠前面的内容
function setIntercept(obj) { var index = obj.lastIndexOf("\/"); obj = obj.substring(0, index + 1); return obj; }
4、截取?后面的内容
function setIntercept0(obj) { var index = obj.lastIndexOf("\?"); obj = obj.substring(index + 1, obj.length); return obj; }
5、UUID
function uuid() { var s = []; var hexDigits = "0123456789abcdef"; for (var i = 0; i < 36; i++) { s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1); } s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010 s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01 s[8] = s[13] = s[18] = s[23] = "-"; var uuid = s.join(""); return uuid; }
6、Base64加解密
var b = new Base64();
b.encode(加密数据)
b.decode(解密数据)
function Base64() { _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; this.encode = function(input) { var output = ""; var chr1, chr2, chr3, enc1, enc2, enc3, enc4; var i = 0; input = _utf8_encode(input); while (i < input.length) { chr1 = input.charCodeAt(i++); chr2 = input.charCodeAt(i++); chr3 = input.charCodeAt(i++); enc1 = chr1 >> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); enc4 = chr3 & 63; if (isNaN(chr2)) { enc3 = enc4 = 64; } else if (isNaN(chr3)) { enc4 = 64; } output = output + _keyStr.charAt(enc1) + _keyStr.charAt(enc2) + _keyStr.charAt(enc3) + _keyStr.charAt(enc4); } return output; } this.decode = function(input) { var output = ""; var chr1, chr2, chr3; var enc1, enc2, enc3, enc4; var i = 0; input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); while (i < input.length) { enc1 = _keyStr.indexOf(input.charAt(i++)); enc2 = _keyStr.indexOf(input.charAt(i++)); enc3 = _keyStr.indexOf(input.charAt(i++)); enc4 = _keyStr.indexOf(input.charAt(i++)); chr1 = (enc1 << 2) | (enc2 >> 4); chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); chr3 = ((enc3 & 3) << 6) | enc4; output = output + String.fromCharCode(chr1); if (enc3 != 64) { output = output + String.fromCharCode(chr2); } if (enc4 != 64) { output = output + String.fromCharCode(chr3); } } output = _utf8_decode(output); return output; } _utf8_encode = function(string) { string = string.replace(/\r\n/g, "\n"); var utftext = ""; for (var n = 0; n < string.length; n++) { var c = string.charCodeAt(n); if (c < 128) { utftext += String.fromCharCode(c); } else if ((c > 127) && (c < 2048)) { utftext += String.fromCharCode((c >> 6) | 192); utftext += String.fromCharCode((c & 63) | 128); } else { utftext += String.fromCharCode((c >> 12) | 224); utftext += String.fromCharCode(((c >> 6) & 63) | 128); utftext += String.fromCharCode((c & 63) | 128); } } return utftext; } _utf8_decode = function(utftext) { var string = ""; var i = 0; var c = c1 = c2 = 0; while (i < utftext.length) { c = utftext.charCodeAt(i); if (c < 128) { string += String.fromCharCode(c); i++; } else if ((c > 191) && (c < 224)) { c2 = utftext.charCodeAt(i + 1); string += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); i += 2; } else { c2 = utftext.charCodeAt(i + 1); c3 = utftext.charCodeAt(i + 2); string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); i += 3; } } return string; } }
7、iframe 内外传参
iframeName.textInput(传的参数); iframeName是iframe的name属性 textInput()是iframe嵌入页的函数名 document.getElementById('iframe').contentWindow.playerParameter = '父页面传值'; console.log(document.getElementById('iframe').contentWindow. playerParameter )
8、微信窗口关闭
WeixinJSBridge.invoke('closeWindow', {}, function(rs) {});
9、获取当前时间戳
第一种方法:
var timestamp = Date.parse(new Date());
结果:1280977330000
第二种方法:
var timestamp = (new Date()).valueOf();
结果:1280977330748
第三种方法:
var timestamp=new Date().getTime();
结果:1280977330748
以上代码将获取从 1970年1月1日午夜开始的毫秒数。二者的区别是,第一种方法的毫秒位上为全零,即只是精确到秒的毫秒数
jQuery 获取时间戳 $.now()
var timestamp = $.now();
当前时间时间戳
Math.round(new Date().getTime()/1000)
10、JS异步加载
有时候加载JS文件慢,可能造成网页失去响应。解决办法有两个,一个是把它放在网页底部加载,另一个是写成下面这样:
async属性表明这个文件需要异步加载,避免网页失去响应。IE不支持这个属性,只支持defer,所以把defer也写上。
11、清除空格
String.prototype.trim = function() { var reExtraSpace = /^\s*(.*?)\s+$/; return this.replace(reExtraSpace, "$1") }
12、清除左空格/右空格
function ltrim(s){ return s.replace( /^(\s*| *)/, ""); } function rtrim(s){ return s.replace( /(\s*| *)$/, ""); }
13、字符串长度截取
function cutstr(str, len) { var temp, icount = 0, patrn = /[^\x00-\xff]/, strre = ""; for (var i = 0; i < str.length; i++) { if (icount < len - 1) { temp = str.substr(i, 1); if (patrn.exec(temp) == null) { icount = icount + 1 } else { icount = icount + 2 } strre += temp } else { break; } } return strre + "..." }
14、判断是否为数字类型
function isDigit(value) { var patrn = /^[0-9]*$/; if (patrn.exec(value) == null || value == "") { return false } else { return true } }
15、加入收藏夹
function AddFavorite(sURL, sTitle) { try { window.external.addFavorite(sURL, sTitle) } catch(e) { try { window.sidebar.addPanel(sTitle, sURL, "") } catch(e) { alert("加入收藏失败,请使用Ctrl+D进行添加") } } }
16、设为首页
function setHomepage() { if (document.all) { document.body.style.behavior = 'url(#default#homepage)'; document.body.setHomePage('http://w3cboy.com') } else if (window.sidebar) { if (window.netscape) { try { netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect") } catch(e) { alert("该操作被浏览器拒绝,如果想启用该功能,请在地址栏内输入 about:config,然后将项 signed.applets.codebase_principal_support 值该为true") } } var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch); prefs.setCharPref('browser.startup.homepage', 'http://w3cboy.com') } }
17、加载样式文件
function LoadStyle(url) { try { document.createStyleSheet(url) } catch(e) { var cssLink = document.createElement('link'); cssLink.rel = 'stylesheet'; cssLink.type = 'text/css'; cssLink.href = url; var head = document.getElementsByTagName('head')[0]; head.appendChild(cssLink) } }
18、检验URL链接是否有效
function getUrlState(URL){ var xmlhttp = new ActiveXObject("microsoft.xmlhttp"); xmlhttp.Open("GET",URL, false); try{ xmlhttp.Send(); }catch(e){ }finally{ var result = xmlhttp.responseText; if(result){ if(xmlhttp.Status==200){ return(true); }else{ return(false); } }else{ return(false); } } }
19、格式化CSS样式代码
function formatCss(s){//格式化代码 s = s.replace(/\s*([\{\}\:\;\,])\s*/g, "$1"); s = s.replace(/;\s*;/g, ";"); //清除连续分号 s = s.replace(/\,[\s\.\#\d]*{/g, "{"); s = s.replace(/([^\s])\{([^\s])/g, "$1 {\n\t$2"); s = s.replace(/([^\s])\}([^\n]*)/g, "$1\n}\n$2"); s = s.replace(/([^\s]);([^\s\}])/g, "$1;\n\t$2"); return s; }
20、压缩CSS样式代码
function compressCss (s) {//压缩代码 s = s.replace(/\/\*(.|\n)*?\*\//g, ""); //删除注释 s = s.replace(/\s*([\{\}\:\;\,])\s*/g, "$1"); s = s.replace(/\,[\s\.\#\d]*\{/g, "{"); //容错处理 s = s.replace(/;\s*;/g, ";"); //清除连续分号 s = s.match(/^\s*(\S+(\s+\S+)*)\s*$/); //去掉首尾空白 return (s == null) ? "" : s[1]; }
21、判断是否移动设备
function isMobile(){ if (typeof this._isMobile === 'boolean'){ return this._isMobile; } var screenWidth = this.getScreenWidth(); var fixViewPortsExperiment = rendererModel.runningExperiments.FixViewport ||rendererModel.runningExperiments.fixviewport; var fixViewPortsExperimentRunning = fixViewPortsExperiment && (fixViewPortsExperiment.toLowerCase() === "new"); if(!fixViewPortsExperiment){ if(!this.isAppleMobileDevice()){ screenWidth = screenWidth/window.devicePixelRatio; } } var isMobileScreenSize = screenWidth < 600; var isMobileUserAgent = false; this._isMobile = isMobileScreenSize && this.isTouchScreen(); return this._isMobile; }
22、判断是否移动设备访问
function isMobileUserAgent(){ return (/iphone|ipod|android.*mobile|windows.*phone|blackberry.*mobile/i.test(window.navigator.userAgent.toLowerCase())); }
23、判断是否苹果移动设备访问
function isAppleMobileDevice(){ return (/iphone|ipod|ipad|Macintosh/i.test(navigator.userAgent.toLowerCase())); }
24、判断是否安卓移动设备访问
function isAndroidMobileDevice(){ return (/android/i.test(navigator.userAgent.toLowerCase())); }
25、获取移动设备初始化大小
function getInitZoom(){ if(!this._initZoom){ var screenWidth = Math.min(screen.height, screen.width); if(this.isAndroidMobileDevice() && !this.isNewChromeOnAndroid()){ screenWidth = screenWidth/window.devicePixelRatio; } this._initZoom = screenWidth /document.body.offsetWidth; } return this._initZoom; }
26、获取移动设备屏幕宽度
function getScreenWidth(){ var smallerSide = Math.min(screen.width, screen.height); var fixViewPortsExperiment = rendererModel.runningExperiments.FixViewport || rendererModel.runningExperiments.fixviewport; var fixViewPortsExperimentRunning = fixViewPortsExperiment && (fixViewPortsExperiment.toLowerCase() === "new"); if(fixViewPortsExperiment){ if(this.isAndroidMobileDevice() && !this.isNewChromeOnAndroid()){ smallerSide = smallerSide/window.devicePixelRatio; } } return smallerSide; }
27、完美判断是否为网址
function IsURL(strUrl) { var regular = /^\b(((https?|ftp):\/\/)?[-a-z0-9]+(\.[-a-z0-9]+)*\.(?:com|edu|gov|int|mil|net|org|biz|info|name|museum|asia|coop|aero|[a-z][a-z]|((25[0-5])|(2[0-4]\d)|(1\d\d)|([1-9]\d)|\d))\b(\/[-a-z0-9_:\@&?=+,.!\/~%\$]*)?)$/i if (regular.test(strUrl)) { return true; }else { return false; } }
28、获取页面高度
function getPageHeight(){ var g = document, a = g.body, f = g.documentElement, d = g.compatMode == "BackCompat" ? a : g.documentElement; return Math.max(f.scrollHeight, a.scrollHeight, d.clientHeight); }
29、获取页面可视宽度
function getPageViewWidth(){ var d = document, a = d.compatMode == "BackCompat" ? d.body : d.documentElement; return a.clientWidth; }
30、获取页面宽度
function getPageWidth(){ var g = document, a = g.body, f = g.documentElement, d = g.compatMode == "BackCompat" ? a : g.documentElement; return Math.max(f.scrollWidth, a.scrollWidth, d.clientWidth); }
31、获取页面scrollTop
function getPageScrollTop(){ var a = document; return a.documentElement.scrollTop || a.body.scrollTop; }
32、获取页面可视高度
function getPageViewHeight() { var d = document, a = d.compatMode == "BackCompat" ? d.body : d.documentElement; return a.clientHeight; }
33、去掉url前缀
function removeUrlPrefix(a){ a=a.replace(/:/g,":").replace(/./g,".").replace(///g,"/"); while(trim(a).toLowerCase().indexOf("http://")==0){ a=trim(a.replace(/http:\/\//i,"")); } return a; }
34、全角半角转换
//iCase: 0全到半,1半到全,其他不转化 function chgCase(sStr,iCase){ if(typeof sStr != "string" || sStr.length <= 0 || !(iCase === 0 || iCase == 1)){ return sStr; } var i,oRs=[],iCode; if(iCase){/*半->全*/ for(i=0; i<sStr.length;i+=1){ iCode = sStr.charCodeAt(i); if(iCode == 32){ iCode = 12288; }else if(iCode < 127){ iCode += 65248; } oRs.push(String.fromCharCode(iCode)); } }else{/*全->半*/ for(i=0; i<sStr.length;i+=1){ iCode = sStr.charCodeAt(i); if(iCode == 12288){ iCode = 32; }else if(iCode > 65280 && iCode < 65375){ iCode -= 65248; } oRs.push(String.fromCharCode(iCode)); } } return oRs.join(""); }
35、日期格式化函数+调用方法
Date.prototype.format = function(format){ var o = { "M+" : this.getMonth()+1, //month "d+" : this.getDate(), //day "h+" : this.getHours(), //hour "m+" : this.getMinutes(), //minute "s+" : this.getSeconds(), //second "q+" : Math.floor((this.getMonth()+3)/3), //quarter "S" : this.getMilliseconds() //millisecond }; if(/(y+)/.test(format)) format=format.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); for(var k in o){ if(new RegExp("("+ k +")").test(format)) format = format.replace(RegExp.$1,RegExp.$1.length==1 ? o[k] :("00"+ o[k]).substr((""+ o[k]).length)); } return format; } alert(new Date().format("yyyy-MM-dd hh:mm:ss"));
36、时间个性化输出功能
/* 1、< 60s, 显示为“刚刚” 2、>= 1min && < 60 min, 显示与当前时间差“XX分钟前” 3、>= 60min && < 1day, 显示与当前时间差“今天 XX:XX” 4、>= 1day && < 1year, 显示日期“XX月XX日 XX:XX” 5、>= 1year, 显示具体日期“XXXX年XX月XX日 XX:XX” */ function timeFormat(time){ var date = new Date(time), curDate = new Date(), year = date.getFullYear(), month = date.getMonth() + 10, day = date.getDate(), hour = date.getHours(), minute = date.getMinutes(), curYear = curDate.getFullYear(), curHour = curDate.getHours(), timeStr; if(year < curYear){ timeStr = year +'年'+ month +'月'+ day +'日 '+ hour +':'+ minute; }else{ var pastTime = curDate - date, pastH = pastTime/3600000; if(pastH > curHour){ timeStr = month +'月'+ day +'日 '+ hour +':'+ minute; }else if(pastH >= 1){ timeStr = '今天 ' + hour +':'+ minute +'分'; }else{ var pastM = curDate.getMinutes() - minute; if(pastM > 1){ timeStr = pastM +'分钟前'; }else{ timeStr = '刚刚'; } } } return timeStr; }
37、解决offsetX兼容性问题
// 针对火狐不支持offsetX/Y function getOffset(e){ var target = e.target, // 当前触发的目标对象 eventCoord, pageCoord, offsetCoord; // 计算当前触发元素到文档的距离 pageCoord = getPageCoord(target); // 计算光标到文档的距离 eventCoord = { X : window.pageXOffset + e.clientX, Y : window.pageYOffset + e.clientY }; // 相减获取光标到第一个定位的父元素的坐标 offsetCoord = { X : eventCoord.X - pageCoord.X, Y : eventCoord.Y - pageCoord.Y }; return offsetCoord; } function getPageCoord(element){ var coord = { X : 0, Y : 0 }; // 计算从当前触发元素到根节点为止, // 各级 offsetParent 元素的 offsetLeft 或 offsetTop 值之和 while (element){ coord.X += element.offsetLeft; coord.Y += element.offsetTop; element = element.offsetParent; } return coord; }
38、返回顶部的通用方法
function backTop(btnId) { var btn = document.getElementById(btnId); var d = document.documentElement; var b = document.body; window.onscroll = set; btn.style.display = "none"; btn.onclick = function() { btn.style.display = "none"; window.onscroll = null; this.timer = setInterval(function() { d.scrollTop -= Math.ceil((d.scrollTop + b.scrollTop) * 0.1); b.scrollTop -= Math.ceil((d.scrollTop + b.scrollTop) * 0.1); if ((d.scrollTop + b.scrollTop) == 0) clearInterval(btn.timer, window.onscroll = set); }, 10); }; function set() { btn.style.display = (d.scrollTop + b.scrollTop > 100) ? 'block': "none" } }; backTop('goTop');
39、提取页面代码中所有网址
var aa = document.documentElement.outerHTML.match(/(url\(|src=|href=)[\"\']*([^\"\'\(\)\<\>\[\] ]+)[\"\'\)]*|(http:\/\/[\w\-\.]+[^\"\'\(\)\<\>\[\] ]+)/ig).join("\r\n").replace(/^(src=|href=|url\()[\"\']*|[\"\'\>\) ]*$/igm,""); alert(aa);
40、清除相同的数组
String.prototype.unique=function(){ var x=this.split(/[\r\n]+/); var y=''; for(var i=0;i<x.length;i++){ if(!new RegExp("^"+x.replace(/([^\w])/ig,"\\$1")+"$","igm").test(y)){ y+=x+"\r\n" } } return y };
41、按字母排序,对每行进行数组排序
function SetSort(){ var text=K1.value.split(/[\r\n]/).sort().join("\r\n");//顺序 var test=K1.value.split(/[\r\n]/).sort().reverse().join("\r\n");//反序 K1.value=K1.value!=text?text:test; }
42、字符串反序(倒序)
function IsReverse(text){ return text.split('').reverse().join(''); }
43、清除html代码中的脚本
function clear_script(){ K1.value=K1.value.replace(/<script.*?>[\s\S]*?<\/script>|\s+on[a-zA-Z]{3,16}\s?=\s?"[\s\S]*?"|\s+on[a-zA-Z]{3,16}\s?=\s?'[\s\S]*?'|\s+on[a-zA-Z]{3,16}\s?=[^ >]+/ig,""); } 动态执行JavaScript脚本 function javascript(){ try{ eval(K1.value); }catch(e){ alert(e.message); } }
44、金额大写转换函数
function transform(tranvalue) { try { var i = 1; var dw2 = new Array("", "万", "亿"); //大单位 var dw1 = new Array("拾", "佰", "仟"); //小单位 var dw = new Array("零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"); //整数部分用 //以下是小写转换成大写显示在合计大写的文本框中 //分离整数与小数 var source = splits(tranvalue); var num = source[0]; var dig = source[1]; //转换整数部分 var k1 = 0; //计小单位 var k2 = 0; //计大单位 var sum = 0; var str = ""; var len = source[0].length; //整数的长度 for (i = 1; i <= len; i++) { var n = source[0].charAt(len - i); //取得某个位数上的数字 var bn = 0; if (len - i - 1 >= 0) { bn = source[0].charAt(len - i - 1); //取得某个位数前一位上的数字 } sum = sum + Number(n); if (sum != 0) { str = dw[Number(n)].concat(str); //取得该数字对应的大写数字,并插入到str字符串的前面 if (n == '0') sum = 0; } if (len - i - 1 >= 0) { //在数字范围内 if (k1 != 3) { //加小单位 if (bn != 0) { str = dw1[k1].concat(str); } k1++; } else { //不加小单位,加大单位 k1 = 0; var temp = str.charAt(0); if (temp == "万" || temp == "亿") //若大单位前没有数字则舍去大单位 str = str.substr(1, str.length - 1); str = dw2[k2].concat(str); sum = 0; } } if (k1 == 3){ //小单位到千则大单位进一 k2++; } } //转换小数部分 var strdig = ""; if (dig != "") { var n = dig.charAt(0); if (n != 0) { strdig += dw[Number(n)] + "角"; //加数字 } var n = dig.charAt(1); if (n != 0) { strdig += dw[Number(n)] + "分"; //加数字 } } str += "元" + strdig; } catch(e) { return "0元"; } return str; } //拆分整数与小数 function splits(tranvalue) { var value = new Array('', ''); temp = tranvalue.split("."); for (var i = 0; i < temp.length; i++) { value = temp; } return value; }
45、js阻止冒泡事件
function stopPropagation(e) { e = e || window.event; if(e.stopPropagation) { //W3C阻止冒泡方法 e.stopPropagation(); } else { e.cancelBubble = true; //IE阻止冒泡方法 } }
46、判断某值知否在数组中
Array.prototype.isContainsValue=function(value) { for(var i in this){ if(this[i]==value){ return true; } } return false; };
47、根据一个值删除某元素
Array.prototype.delByValue=function(value) { for(var i = 0;i<this.length;i++){ if(this[i] == value){ this.del(i); } } };
48、根据下标删除某元素
Array.prototype.del=function(n) { if(n<0) return this; else return this.slice(0,n).concat(this.slice(n+1,this.length)); };
49、检查密码强度
$('#pass').keyup(function (e) { var strongRegex = new RegExp("^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\W).*$", "g"); var mediumRegex = new RegExp("^(?=.{7,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$", "g"); var enoughRegex = new RegExp("(?=.{6,}).*", "g"); if (false == enoughRegex.test($(this).val())) { $('#passstrength').html('More Characters'); } else if (strongRegex.test($(this).val())) { $('#passstrength').className = 'ok'; $('#passstrength').html('强!'); } else if (mediumRegex.test($(this).val())) { $('#passstrength').className = 'alert'; $('#passstrength').html('中!'); } else { $('#passstrength').className = 'error'; $('#passstrength').html('弱!'); } return true; } );
50、js去除字符串中特殊符号
var a = 'dsfhhdifhg%dfg#dfhgfh' var b = a.replace(/[&\|\\\*^%$#@\-]/g,""); console.log(b) 输出 b = 'dsfhhdifhgdfgdfhgfh'
秒转成时分秒格式
function musicTimeFormat(value) { var theTime = parseInt(value); // 秒 var theTime1 = 0; // 分 var theTime2 = 0; // 小时 // alert(theTime); if (theTime > 60) { theTime1 = parseInt(theTime / 60); theTime = parseInt(theTime % 60); if (theTime1 > 60) { theTime2 = parseInt(theTime1 / 60); theTime1 = parseInt(theTime1 % 60); } } var result = "" + parseInt(theTime) + "秒"; if (theTime1 > 0) { result = "" + parseInt(theTime1) + "分" + result; } if (theTime2 > 0) { result = "" + parseInt(theTime2) + "小时" + result; } return result; }
51、数组去重
方法一: Array.prototype.distinct = function(){ var arr = this, result = [], i, j, len = arr.length; for(i = 0; i < len; i++){ for(j = i + 1; j < len; j++){ if(arr[i] === arr[j]){ j = ++i; } } result.push(arr[i]); } return result; } var arra = [1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3,3,2,3,3,2,2,1,23,1,23,2,3,2,3,2,3]; arra.distinct(); //返回[1, 23, 2, 3] 方法二: Array.prototype.distinct = function (){ var arr = this, i, obj = {}, result = [], len = arr.length; for(i = 0; i< arr.length; i++){ if(!obj[arr[i]]){ //如果能查找到,证明数组元素重复了 obj[arr[i]] = 1; result.push(arr[i]); } } return result; }; var a = [1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3,3,2,3,3,2,2,1,23,1,23,2,3,2,3,2,3]; var b = a.distinct(); console.log(b.toString()); //1,2,3,23 方法三: Array.prototype.distinct = function (){ var arr = this, result = [], len = arr.length; arr.forEach(function(v, i ,arr){ //这里利用map,filter方法也可以实现 var bool = arr.indexOf(v,i+1); //从传入参数的下一个索引值开始寻找是否存在重复 if(bool === -1){ result.push(v); } }) return result; }; var a = [1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3,3,2,3,3,2,2,1,23,1,23,2,3,2,3,2,3]; var b = a.distinct(); console.log(b.toString()); //1,23,2,3 方法四: function arrRmRepeat(arr) { var newArr = []; for (var i = 0; i < arr.length; i++) { if (newArr.indexOf(arr[i]) == -1) { newArr.push(arr[i]) } } return newArr; } 方法五: function arrRmRepeat(arr) { return [...new Set(arr)]; }
52、合并数组并去重
方法一: function concatArr(arr1, arr2){ var arr = arr1.concat(arr2); arr = unique1(arr);//再引用上面的任意一个去重方法 return arr; } 方法二: var a = [1, 2, 3]; var b = [4, 5, 6]; Array.prototype.push.apply(a, b);//a=[1,2,3,4,5,6] //等效于:a.push.apply(a, b); //也等效于[].push.apply(a, b); function concatArray(arr1,arr2){ Array.prototype.push.apply(arr1, arr2); arr1 = unique1(arr1); return arr1; }
53、数组升降序
升序: array.sort(function (x,y) { return x-y; }); 降序: array.sort(function (x,y) { return y-x; });
54、JSON排序
按照id排序 json.sort( function(x,t){ return x.id-t.id } )