常用方法
Posted 我有小蛮腰
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了常用方法相关的知识,希望对你有一定的参考价值。
/** * 通用方法的声明 */ // 通用方法 //获取小数点后num位,x 传入的小数, num 获取小数点后几位 var changeTwoDecimal_f = exports.changeTwoDecimal_f = function(x, num){ var f_x = parseFloat(x); if (isNaN(f_x)) { alert(‘function:changeTwoDecimal->parameter error‘); return false; } var f_x = Math.round(x * 100) / 100; var s_x = f_x.toString(); var pos_decimal = s_x.indexOf(‘.‘); if (pos_decimal < 0) { pos_decimal = s_x.length; s_x += ‘.‘; } while (s_x.length <= pos_decimal + (num-1)) { s_x += ‘0‘; } return parseFloat(s_x); }; var typeOf = exports.typeOf = function(item) { if (Array.isArray(item)) return ‘array‘; return typeof(item); }; // 复制对象(对array和object递归) // 无法复制构造函数等内容 var cloneOf = exports.cloneOf = function (item) { var clone; var i; switch (typeOf(item)) { case ‘array‘: i = item.length; clone = new Array(i); var i = item.length; while (i--) clone[i] = cloneOf(item[i]); break case ‘object‘: clone = {}; for (var key in item) clone[key] = cloneOf(item[key]); break; default: clone = item; break; } return clone; }; // 加权随机 // list为随机项列表,单项的结构为{value:1, weight:200} var random_weight = exports.random_weight = function(list) { // 计算总权重 var total = 0; for (var i = 0; i < list.length; i++) { if (list[i]) total += list[i].weight; } // 获取随机数 var rand = Math.random() * total; // 匹配随机项 var curr_weight = 0; for (var i = 0; i < list.length; i++) { if (list[i]) { curr_weight += list[i].weight; if (curr_weight > rand) return list[i]; } } return null; }; /** * 从权重字典中随机 */ var randomWeightDict = exports.randomWeightDict = function (dict) { var weight = 0; for (var key in dict) { weight += dict[key]; } var rand = Math.random() * weight; for (var key in dict) { weight -= dict[key]; if (weight <= rand) { return key; } } return null; }; // 加权随机排序, 权重大的越容易排在前面 // list为随机项列表,单项的结构为{value:1, weight:200} // 返回顺序号(0表示第一个list[0]); var random_weight_sort = exports.random_weight_sort = function (list) { // 计算总权重 var total = 0; var pos = []; for (var i = 0; i < list.length; i++) { if (list[i]) { total += list[i].weight; pos.push({idx: i, weight: list[i].weight}); } } for (var p = 0; p < pos.length-1; p++) { // 获取随机数 var rand = Math.random() * total; // 匹配随机项 var curr_weight = 0; var cur_pos = p; while (cur_pos < pos.length) { curr_weight += pos[cur_pos].weight; if (curr_weight >= rand) { break; } cur_pos++; } var t = pos[cur_pos]; pos[cur_pos] = pos[p]; pos[p] = t; total -= t.weight; } var idx = []; for (var j = 0; j < pos.length; ++j) { idx.push(pos[j].idx); } return idx; }; // 不重复的加权随机 // arr : [{weight: N, ...}] var random_weight_arr = exports.random_weight_arr = function (arr, count) { // 计算总权重 if (arr.length < count) { return null; } if (count == 0) { return []; } if (count == arr.length) return arr; // 构造备选数组 var tmp_arr = []; for (var i = 0; i < arr.length; ++i) { tmp_arr.push({weight: arr[i].weight, idx: i, val: arr[i]}); } // 随机选 var result = []; for (var i = 0; i < count; i++) { var r = random_weight(tmp_arr); if (!r) { // 出错 return null; } result.push(r.val); r.weight = 0; // 退出备选 } return result; }; // 整数随机 var random_int = exports.random_int = function(from, to) { return Math.floor(from + Math.random() * (to - from + 1)); }; // 间隔随机 var random_gap = exports.random_gap = function(from, to, interval) { var length = Math.floor((to - from) / interval); var result = random_int(0, length); return from + interval * result; }; // 小数随机 var random = exports.random = function(from, to) { return from + Math.random() * (to - from); }; // 四舍五入保留n位小数 var decimal = exports.decimal = function(num, n) { var w = Math.pow(10, n); return Math.round(num*w)/w; }; //从数组arr中随机取count个不重复的元素 var random_arr = exports.random_arr = function(arr, count) { if (typeOf(arr) != ‘array‘) return []; if (count >= arr.length) return arr; var mark = {}; var result = []; var len = arr.length - 1; for (var i = 0; i < count; i ++) { var index = random_int(0, len); if (mark[index] == undefined) { result.push(arr[index]); } else { result.push(arr[mark[index]]); } //模拟放到末尾,随机到的位置标记成最后那个 if (mark[len] == undefined) mark[index] = len; else mark[index] = mark[len]; len --; } return result; }; // 随机选择 // 返回n个数, 取值是0~N-1 var random_select = exports.random_select = function (N, n) { if (N <= 0 || n <= 0) return []; var r = []; // 记录结果 var t = {}; // 记录替换 for (var i = 0; i < n; ++i) { var pos = N - 1 - i; var posV = pos; if (t[pos] !== undefined) posV = t[pos]; var p = random_int(0, pos); var pV = p; if (t[p] !== undefined) pV = t[p]; r.push(p); t[p] = posV; } // 排序 r.sort(function (a, b) { return a - b; }); return r; }; // 随机洗牌 // N: 需要洗牌的数量 // 返回长度为N的数组, 里面是0~N-1这N个数,已经随机排列 var random_shuffle = exports.random_shuffle = function (N) { if (N <= 0) return []; var r = [0]; for (var i = 1; i < N; ++i) { r.push(i); var pos = random_int(0, i); if (pos != i) { var t = r[pos]; r[pos] = r[i]; r[i] = t; } } return r; }; // 从array或者obj中随机选择一个 // 返回序号或者key // 失败返回null var random_selectOne = exports.random_selectOne = function (obj) { if (obj instanceof Array) { if (obj.length < 1) return null; return random_int(0, obj.length - 1); } else if (typeof (obj) == ‘object‘) { var arr = []; for (var k in obj) arr.push(k); if (arr.length < 1) return null; return arr[random_int(0, arr.length - 1)]; } return null; }; // 检查数组中是否包含某个元素 // 返回true或false var isInArray = exports.isInArray = function (arrs, value) { if (typeOf(arrs) != ‘array‘) return false; for (var i=0; i<arrs.length; i++) { var arr = arrs[i]; if (arr == value) { return true; } } return false; }; var __UUID_CHARS = ‘0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz‘.split(‘‘); exports.uuid = function (len, radix){ var chars = __UUID_CHARS, uuid = [], rnd = Math.random; radix = radix || chars.length; if (len){ for (var i = 0; i < len; i++) uuid[i] = chars[0 | rnd()*radix]; } else { var r; uuid[8] = uuid[13] = uuid[18] = uuid[23] = ‘-‘; uuid[14] = ‘4‘; for (var i = 0; i < 36; i++){ if (!uuid[i]) { r = 0 | rnd()*16; uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r & 0xf]; } } } return uuid.join(‘‘); }; exports.inTheSameDay = function(t1, t2) { if (!t1 || !t2) return false; return new Date(t1*1000).toDateString() == new Date(t2*1000).toDateString(); }; exports.inTheSameWeek = function(t1, t2) { if (!t1 || !t2) return false; t1 = t1 * 1000; t2 = t2 * 1000; var date1 = new Date(t1); var dayOfWeek1 = (date1.getDay()==0 ? 7 : date1.getDay()); var date3 = new Date(date1.getFullYear(), date1.getMonth(), date1.getDate()); var t3 = date3.getTime() - (dayOfWeek1-1) * 86400000; var t4 = t3 + 7 * 86400000; if (t3 <= t2 && t2 < t4) return true; else return false; }, // 每周开始 // 周一凌晨 0:00 exports.getWeekStart = function(t1) { if (t1 === undefined || t1 === null) { t1 = getNow(); } t1 = t1 * 1000; var date1 = new Date(t1); var dayOfWeek1 = (date1.getDay()==0 ? 7 : date1.getDay()); // 周几 1~7 var date3 = new Date(date1.getFullYear(), date1.getMonth(), date1.getDate()); var startTime = date3.getTime() - (dayOfWeek1-1) * 86400000; return Math.floor(startTime / 1000); }, exports.inTheSameMonth = function(t1, t2) { if (!t1 || !t2) return false; var date1 = new Date(t1 * 1000); var date2 = new Date(t2 * 1000); if (date1.getFullYear() == date2.getFullYear() && date1.getMonth() == date2.getMonth()) return true; else return false; }; exports.lastSecondOfDay = function(time) { var date = new Date(time * 1000); date.setHours(23); date.setMinutes(59); date.setSeconds(59); return Math.floor(date.getTime() / 1000); }; exports.getSomeDayTime = function(time, hmsFormat) { var date = new Date(time * 1000); var format = formatDate(date); return getTime(format.split(‘ ‘)[0] + ‘ ‘ + hmsFormat); }; exports.getTodayTime = function(hmsFormat) { var date = new Date(); var format = formatDate(date); return getTime(format.split(‘ ‘)[0] + ‘ ‘ + hmsFormat); }; var getTime = exports.getTime = function(format) { var tmp = format.split(‘ ‘); var day = tmp[0]; var time = tmp[1] || ‘00:00:00‘; var day = day.split(‘-‘); if(!day[2]) day[2] = ‘01‘; var time = time.split(‘:‘); var date = new Date(day[0],day[1]-1,day[2],time[0]||0,time[1]||0,time[2]||0,0); return Math.floor(date.getTime()/1000); }; // 字符串转为秒 // "dd hh:mm:ss" 或者 "hh:mm:ss" 或者 "hh:mm" var stringToSecond = exports.stringToSecond = function (d_hms) { var day = 0; var sec = 0; var tmp = d_hms.split(‘ ‘); if (tmp.length > 1) { day = +tmp[0]; tmp = tmp[1].split(‘:‘); } else { tmp = tmp[0].split(‘:‘); } sec = (+tmp[0]) * 3600 + (+tmp[1]) * 60; if (tmp.length >= 3) { sec += (+tmp[2]); } sec += (day * 24 * 3600); return sec; }; // time的时间单位为秒 exports.isInTheDateRange = function(time, start, end) { var start_time = getTime(start); var end_time = getTime(end); if (time > start_time && time < end_time) return true; return false; }; exports.isInTheDateRangeEx = function(time, start, end) { var start_time = getTime(start); var end_time = getTime(end); if (time >= start_time && time <= end_time) return true; return false; }; var getNow = exports.getNow = function() { return Math.floor(Date.now()/1000); }; exports.getToday = function() { var date = new Date(); date.setHours(0); date.setMinutes(0); date.setSeconds(0); return Math.floor(date/1000); }; //获取第day天后0点时间戳 time为时间戳 exports.getTimestamp = function(time, day) { var date = new Date(time * 1000); date.setHours(0); date.setMinutes(0); date.setSeconds(0); var timestamp = 0; if(!isNaN(parseInt(day))){ timestamp = day * 24 * 3600; } return Math.floor(date.getTime() / 1000) + Math.floor(timestamp); }; exports.getUnixTime = function(date) { var arr = date.split(‘-‘).map(function(a){return +a;}) var newDate = new Date(arr[0], arr[1] - 1, arr[2], 0, 0, 0, 0); return newDate.getTime(); }; //获取某年月1号 exports.getYearMonthFirstDay = function(date) { if(!date) date = new Date(); var year = date.getFullYear(); var month = date.getMonth() + 1; if (month < 10) month = ‘0‘ + month; return ‘‘ + year + ‘-‘ + month + ‘-‘+ ‘01‘; }; var formatDate = exports.formatDate = function(date) { var year = date.getFullYear(); var month = date.getMonth() + 1; if (month < 10) month = ‘0‘ + month; var day = date.getDate(); if (day < 10) day = ‘0‘ + day; var hour = date.getHours(); if (hour < 10) hour = ‘0‘ + hour; var minute = date.getMinutes(); if (minute < 10) minute = ‘0‘ + minute; var second = date.getSeconds(); if (second < 10) second = ‘0‘ + second; return ‘‘ + year + ‘-‘ + month + ‘-‘+ day + ‘ ‘ + hour + ‘:‘ + minute + ‘:‘ + second; }; //返回yyyy-mm-dd var formatDate2 = exports.formatDate2 = function(date) { var year = date.getFullYear(); var month = date.getMonth() + 1; if (month < 10) month = ‘0‘ + month; var day = date.getDate(); if (day < 10) day = ‘0‘ + day; return ‘‘ + year + ‘-‘ + month + ‘-‘+ day; }; //判断输入字符串是否是有效日期格式 (1) yyyy-mm-dd (2) yyyy-mm-dd hh:mm:ss (3) yyyy-mm-dd hh:mm exports.isDate = function(strDate) { try{ var tmp = strDate.split(‘ ‘); if(!tmp[1])tmp[1]=‘1:1‘; var days = tmp[0].split(‘-‘); var times = tmp[1].split(‘:‘); if(days.length!=3)return false; if(!(times.length==2 || times.length==3))return false; for(var i=0;i<days.length;i++){ if(isNaN(parseInt(days[i])))return false; } for(var i=0;i<times.length;i++){ if(isNaN(parseInt(times[i])))return false; } var year = parseInt(days[0], 10); if(year<1 || year>9999)return false; var month = parseInt(days[1], 10); if(month<1 || month>12)return false; var day = parseInt(days[2], 10); var maxDay =31; if(month==4 || month==6 || month==9 ||month ==11)maxDay =30; if(month==2){ if(year%4 != 0) maxDay = 28; else if(year%100==0 && year%400!=0) maxDay = 28; else maxDay = 29; } if(day<1 || day>maxDay)return false; var hour = parseInt(times[0], 10); if(hour<0 || hour>23)return false; var minute = parseInt(times[1], 10); if(minute<0 || minute>59)return false; if(times.length == 3){ var sec = parseInt(times[2], 10); if(sec<0 || sec>59)return false; } return true; }catch(e){ return false; } }; exports.dateDiff = function(time1, time2) { var date1 = new Date(time1 * 1000); var date2; if (time2 == undefined) { date2 = new Date(); } else date2 = new Date(time2 * 1000); date1.setHours(0); date1.setMinutes(0); date1.setSeconds(0); date2.setHours(0); date2.setMinutes(0); date2.setSeconds(0); return Math.round((date2 - date1)/86400000) + 1; }; // same as dateDiff but minus 1 exports.dateDiff2 = function(time1, time2) { var date1 = new Date(time1 * 1000); var date2; if (time2 == undefined) { date2 = new Date(); } else date2 = new Date(time2 * 1000); date1.setHours(0); date1.setMinutes(0); date1.setSeconds(0); date2.setHours(0); date2.setMinutes(0); date2.setSeconds(0); return Math.round((date2 - date1)/86400000); }; //取得将来的周几的几点,对应的秒级时间 time格式11:30 or 11:30:00, weekDay 0-6 exports.getFutureTimeByWeek = function(weekDay, time, from) { var date; if (!from) date = new Date(); else date = new Date(from * 1000); var nowWeekDay = date.getDay(); var nowHour = date.getHours(); var nowMinute = date.getMinutes(); var nowSecond = date.getSeconds(); var tmp = time.split(‘:‘); var futureHour = tmp[0] || 0; var futureMinute = tmp[1] || 0; var futureSecond = tmp[2] || 0; date.setHours(futureHour); date.setMinutes(futureMinute); date.setSeconds(futureSecond); var todayFutureTime = Math.floor(date.getTime()/1000); if (nowWeekDay == weekDay) { var interval = nowHour * 3600 + nowMinute * 60 + nowSecond - futureHour * 3600 - futureMinute * 60 - futureSecond; //时间未到,就是当天了 if (interval <= 0) { return todayFutureTime; } //已经过了时间 else { return todayFutureTime + 86400 * 7; } } else { if (nowWeekDay < weekDay) return todayFutureTime + 86400 * (weekDay - nowWeekDay); else return todayFutureTime + 86400 * (weekDay + 7 - nowWeekDay); } }; // 取符号 var sign = exports.sign = function(a) { if (a > 0) return 1; else if (a < 0) return -1; else return 0; }; //服务器大区前缀 exports.getSvrPrex = function(gId) { var svrId = gId.split(‘-‘)[1]; if (!svrId) return ‘‘; return i18n(‘svrPrex‘, svrId); }; exports.getMaxKey = function(dict) { var max = 0; for (var k in dict) { k = parseInt(k); if (k > max) { max = k; } } return max; }; // 根据key从字典数据中取值,未达到key值的则取前一个key对应的值 exports.getValueFromDictByRange = function(dict, key) { var value = undefined; var final_key = 0; for (var k in dict) { k = parseInt(k); if (key >= k && final_key < k) final_key = k; } if (dict[final_key] != undefined) value = dict[final_key]; return value; }; // 根据key从字典数据中取值,取一个key对应的值 exports.getValueFromDict= function(dict, key) { var value = undefined; var final_key = 0; for (var k in dict) { k = parseInt(k); if (key == k) final_key = k; } if (dict[final_key] != undefined) value = dict[final_key]; return value; }; // 根据key从字典数据中取值,取大于等于key对应的值 exports.getValueFromDictByMax = function(dict, key) { var value = undefined; var max_key = 0; for (var k in dict) { var int_k = parseInt(k); if (max_key < int_k) max_key = int_k; } var final_key = max_key + 1; for (var k in dict) { var int_k = parseInt(k); if (key <= int_k && final_key >= int_k) final_key = int_k; } if (dict[final_key]) value = dict[final_key]; return value; }; // 根据key从字典数据中取值,取大于key对应的值 exports.getValueFromDictByMaxNotEqual = function(dict, key) { var value = undefined; var max_key = 0; for (var k in dict) { var int_k = parseInt(k); if (max_key < int_k) max_key = int_k; } var final_key = max_key + 1; for (var k in dict) { var int_k = parseInt(k); if (key < int_k && final_key >= int_k) final_key = int_k; } if (dict[final_key] != undefined) value = dict[final_key]; return value; }; //校验IP地址格式 exports.isIP = function(strIP) { if (!strIP || ‘‘ == strIP) { return false; } var re = /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/g; //匹配正则表达式 if (re.test(strIP)) { if (RegExp.$1 < 256 && RegExp.$2 < 256 && RegExp.$3 < 256 && RegExp.$3 < 256) { return true; } } return false; }; exports.isInList = function(list, item) { if (!list || !item || ‘‘ == item || list.length == 0) return false; for (var i = 0; i < list.length; i++) { if (item == list[i]) return true; } return false; }; // 判断对象是否是[]或者{} // 各种非Object都返回true exports.isEmpty = function (obj) { for (var name in obj) { return false; } return true; }; // 获取指定的属性 exports.getAttr = function (attrs, getlist, clone) { var attr = {}; for (var i in getlist) { var k = getlist[i]; var v = attrs[k]; if (v === undefined) { continue; } if (clone) { attr[k] = cloneOf(v); } else { attr[k] = v; } } return attr; }; // 将字符串转换成数组 // "123|456|789" ==> [123,456,789] exports.getNumberArray = function (str, splitChar) { if (typeof (str) == ‘number‘) return [str]; if (!str) return []; var ret = []; splitChar = splitChar || "|"; // 默认分隔符 var strArray = ("" + str).split(splitChar); for (var i = 0; i < strArray.length; ++i) { ret.push(Number(strArray[i])); } return ret; }; // 删除数组中指定的值 // 成功删除返回true exports.removeArrayValue = function (arr, value) { if (!(arr instanceof Array)) { return false; } if (value == undefined) { return false; } var idx = arr.indexOf(value); if (idx < 0) { return false; } arr.splice(idx, 1); return true; }; exports.isMoneyName = function (name) { if (!name || typeof (name) !== ‘string‘) { return false; } // 金钱种类定义见 FinanceType for (var k in FinanceType) { if (FinanceType[k] == name) { return true; } } return false; }; // 根据数组中指定的元素进行排序 // 参数 desc/asc 分别代表 倒序 正序 与 执行元素 // 返回符合条件的数组 exports.getSortFun = function (order, sortBy) { var ordAlpah = (order == ‘asc‘) ? ‘>‘ : ‘<‘; var sortFun = new Function(‘a‘, ‘b‘, ‘return a.‘ + sortBy + ordAlpah + ‘b.‘ + sortBy + ‘?1:-1‘); return sortFun; }; exports.isSuccess = function (rate) { return Math.random() < rate; }; //传入两个坐标,返回两个坐标之间的距离 var getDistance = exports.getDistance = function (coordinate1, coordinate2) { var d = 0; if (coordinate1 && coordinate2) { var x1 = coordinate1.x; var y1 = coordinate1.y; var x2 = coordinate2.x; var y2 = coordinate2.y; d = Math.sqrt(Math.pow(x1-x2, 2) + Math.pow(y1-y2, 2)); } return d; }; /* coord1 当前坐标 coord2 目标坐标 h 矩形高 w 矩形宽 根据当前坐标计算中心点坐标 */ exports.isInRectangle = function (coord1, coord2, h, w) { var leftDown = {x: coord1.x - w/2, y: coord1.y}; var rightDown = {x: coord1.x + w/2, y: coord1.y}; var leftUp = {x: coord1.x - w/2, y: coord1.y + h}; var rightUp = {x: coord1.x + w/2, y: coord1.y + h}; if (coord2.x >= leftDown.x && coord2.x <= rightUp.x && coord2.y >= leftDown.y && coord2.y <= rightUp.y) { return true; } return false; }; /* coord1 当前坐标 coord2 目标坐标 h 攻击范围 判断点在圆形范围内 */ exports.isCanAttack = function (coord1, coord2, h) { var isIn = getDistance(coord1, coord2); // 两点坐标小于攻击范围 if (h > isIn) { return true; } return false; }; var find_model_sql = exports.find_model_sql = function (sql, params) { var deferred = new promise.Deferred(); persist.queryModelWithEscape(sql, params, function (err, cursor) { if (err) { deferred.emitSuccess(null); } else { var results = []; cursor.forEach(function (doc) { if (doc != null) { results.push(doc); } }); if (results.length === 0) { deferred.emitSuccess(null); } else { deferred.emitSuccess(results); } } }); return deferred.promise; }; exports.check_seq = function (seq) { //从数据库载入seq记录 var sql = "SELECT name, val FROM nx_sequence"; return find_model_sql(sql, []).then(function (result) { var res_obj = {}; if (result) { var error_seq = []; for (var i = 0; i < result.length; i++) { res_obj[result[i].name] = true; } for (var name in seq) { if (!res_obj[name]) { error_seq.push(name); } } if (error_seq.length > 0) { for (var i = 0; i < error_seq.length; i++) { sys.log("ERROR: sequence " + error_seq[i] + " not found in mysql"); } sys.log("ERROR: sequence not found in mysql, process exit!"); return false; } return true; } else { sys.log(‘ERROR: find nx_sequence record failed! process exit!‘); return false; } }); };
以上是关于常用方法的主要内容,如果未能解决你的问题,请参考以下文章