1、数字千分位格式化
1 2 3 4 5 6 7 8 9 function thousandFormate (number ){ var str = (number||0 ).toString (), result = "" ; while (str.length > 3 ) { result = ',' + str.slice (-3 ) + result; str = str.slice (0 , str.length - 3 ); } if (str) { result = str + result; } return result; }
2、随机整数 随机数的生成我们需要用到Math对象的方法。
random() 方法可返回介于 0 ~ 1 之间的一个随机数 floor()方法对数进行下舍入 ceil()方法对数进行上舍入
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 parseInt (Math .random ()*5 );parseInt (Math .random ()*max, 10 ) + min;parseInt (Math .random ()*max) + min;Math .floor (Math .random ()*max) + min;Math .ceil (Math .random ()* max) + min;function randomArray (min, max, n ){ let m = 0 , array = []; while (m < n){ array.push (parseInt (Math .random ()*(max-min)) + min); m++; } return array; }
3、日期格式化
有个有意思的问题:
1 2 3 4 5 console .log (new Date ('2016/11/16' ).getTime ());console .log (new Date ('2016-11-16' ).getTime ());new Date (1479225600000 );new Date (1479254400000 );
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 function fmtDate (date, fmt ){ var o = { 'M+' : date.getMonth () + 1 , 'd+' : date.getDate (), 'h+' : date.getHours (), 'm+' : date.getMinutes (), 's+' : date.getSeconds (), 'q+' : Math .floor ((date.getMonth () + 3 ) / 3 ), 'S' : date.getMilliseconds () }; 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; }; fmtDate (new Date (),'yyyy-MM-dd hh:mm' );fmtDate (new Date (),'yyyy-MM-dd' );
4、 url中参数获取
1 2 3 4 5 6 7 8 9 10 11 12 13 function getQueryString (url ) { var queryString = url ? url : ((location.search .length ) ? location.search .substr (1 ) : '' ); var urlParams = queryString.split ('&' ); var arr = null ; var result = {}; for (var i = 0 ; i < urlParams.length ; i++) { arr = aParams[i].split ('=' ); if (arr[0 ].length > 0 ) { result[arr[0 ]] = decodeURIComponent (escape (arr[1 ])); } } return result; }
另外,利用正则表达式:
1 2 3 4 5 6 function getQueryString (name ){ var reg = new RegExp ('(^|&)' + name + '=([^&]*)(&|$)' ) var search = window .location .search .substr (1 ) ? window .location .search .substr (1 ) : '' var res = search.match (reg) return res ? res[2 ] : null }
5、获取cookie中相关字段的值
1 2 3 4 5 6 7 8 9 10 11 12 13 14 function getCookie (name ){ var cookieName = encodeURIComponent (name) + '=' , cookieStart = document .cookie .indexOf (cookieName), cookieValue = null ; if (cookieStart > -1 ){ var cookieEnd = document .cookie .indexOf (';' , cookieStart); if (cookieEnd == -1 ){ cookieEnd = document .cookie .length ; } cookieValue = decodeURIComponent (document .cookie .substring (cookieStart + cookieName.length , cookieEnd)); } return cookieValue; }
未完待续,持续更新中