JS的一些小方法
程序员文章站
2022-05-19 18:56:29
...
/**
* 工具类
* @author pengliang create data 2018-06-05
*/
!function ($) {
this.arrayUtils = {
/**
* @author pengliang
* @param array
* @returns {Array}
* 如果参数非数组类型,直接返回一个空数组
* 如果是数组类型返回源数组
*/
getArray: function (array) {
return this.isArray(array) ? array : [];
}
/**
* @author pengliang
* @param o
* @returns {boolean}
* 判断当前是否为数组
*/
, isArray: function (o) {
return Object.prototype.toString.call(o) == '[object Array]';
}
/**
* @author pengliang
* @param array 数组
* @param symbol 符号
* @param field 字段
* 将当前数组以自定符号连接
* 如果array是非数组类型直接返回一个空的字符串
*/
, join: function (array, symbol, field) {
symbol = symbol || "";
if (!this.isArray(array) || array.length == 0) {
return "";
}
var len = array.length;
var resultData = [];
for (var index = 0; index < len; index++) {
var data = array[index];
resultData.push((field ? data[field] : data));
}
return resultData.join(symbol);
},
/**
* @author pengliang
* @param array
* @returns {boolean}
* 是否为空数组
*/
isEmpty: function (array) {
return !array || array.length == 0;
}
}
this.objectUtils = {
/**
* @author pengliang
* @param array
* @returns {object}
* 获取一个不为空的对象
*/
getObject: function (obj) {
return obj || {};
},
/**
* 克隆一个对象
* @author pengliang
* @param obj
* @returns {*}
*/
cloneObject: function (obj) {
return $.extend(true, {}, obj);
}
}
this.strUtils = {
/**
* @author pengliang
* @param source 原字符
* @param newStr 替换字符
* @returns {*}
* 获取一个正确的字符的字符串
* 排除null,undefined非法字符
*/
getStr: function (source, newStr) {
newStr = newStr || "";
return (!source || source == 'null' || source == 'NULL' || source == 'undefined') ? newStr : source;
}
/**
* 字符是否为空
* @author pengliang
* @param str
* @returns {*}
*/
, isEmpty: function (str) {
return !str || str == 'null' || str == 'NULL' || str == 'undefined';
}
/**
* 替换所有出现字符,返回一个新的字符
* @author pengliang
* @param str 被替换字符
* @param symbol 出现字符
* @param data 替换字符
* @returns {*}
*/
, replaceAll: function (str, symbol, data) {
return str.replace(/-/g, data || '');
}
,
/**
* 去掉左空格
*/
ltrim: function (s) {
if (!s) return "";
return s.replace(/(^\s*)/g, "");
}
/**
* 去掉右空格
*/
, rtrim: function (s) {
if (!s) return "";
return s.replace(/(\s*$)/g, "");
}
/**
* 去掉左右空格
* @param s 字符
* @param isCleanExpression 是否清空表情符号
*/
, trim: function (s, isCleanExpression) {
if (!s) return "";
if (isCleanExpression === true) {
s = s.replace(/\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/g, "");
}
return s.replace(/(^\s*)|(\s*$)/g, "");
}
}
this.jsonUtils = {
/**
* @author pengliang
* @param strJson
* @returns {*}
* 将json字符串转为对象
*/
parseJson: function (strJson) {
return typeof strJson === 'string' ? eval('(' + strJson + ')') : strJson;
},
/**
* @author pengliang
* @param json
* @returns {string}
* 将json对象转为字符
*/
toJsonStr: function (json) {
return typeof json === 'object' ? JSON.stringify(json) : json;
}
}
this.validateUtils = {
/**
* 验证是否是int类型参数值
* @author pengliang
* @param numbStr
* @returns {boolean}
*/
isInt: function (numbStr) {
return /^\d+$/.test(numbStr);
}
}
this.dateUtils = {
/**
* 获取本月第一天
* @param pattern 指定日期格式,否则返回日期对象
*/
thisMonthFirstDay: function (pattern) {
var date = new Date(), y = date.getFullYear(), m = date.getMonth();
var firstDay = new Date(y, m, 1);
//var lastDay = new Date(y, m + 1, 0);
return pattern ? firstDay.format(pattern) : firstDay;
}
/**
* 获取本月最后一天
* @param pattern 指定日期格式,否则返回日期对象
* @returns {Date}
*/
, thisMonthLastDay: function (pattern) {
var date = new Date(), y = date.getFullYear(), m = date.getMonth();
var lastDay = new Date(y, m + 1, 0);
return pattern ? lastDay.format(pattern) : lastDay;
}
/**
* 日期格式化 刚刚、分钟、小时、天、月日时分
* @param date 指定日期格式,否则返回日期对象
*
* @returns {Date}
*/
, formatTime: function (date) {
if (!date) {
return "";
}
if (typeof date === "string") {
date = date.replace(/\-/g, "/");
}
const d = new Date(date);
const dTime = d.getTime();
const now = new Date().getTime();
const diff = (now - dTime) / 1000;
if (diff < 30) {
return "刚刚";
} else if (diff < 3600) {
// less 1 hour
return Math.ceil(diff / 60) + "分钟前";
} else if (diff < 3600 * 24) {
return Math.ceil(diff / 3600) + "小时前";
} else if (diff < 3600 * 24 * 2) {
return "1天前";
}
return (
d.getMonth() +
1 +
"月" +
d.getDate() +
"日" +
d.getHours() +
"时" +
d.getMinutes() +
"分"
);
},
/**
* 格式化日期
* @param time 日期
* @param format 格式默认 yyyy-MM-dd HH:mm:ss
*/
formatDate: function (time, format) {
if (!time) {
return "";
}
if (!format) {
format = "yyyy-MM-dd HH:mm:ss";
}
if (typeof time === "string") {
time = time.replace(/-/g, "/");
}
var date = new Date(time);
var tf = function (i) {
return (i < 10 ? "0" : "") + i;
};
return format.replace(/yyyy|MM|dd|HH|mm|ss/g, function (a) {
switch (a) {
case "yyyy":
return tf(date.getFullYear());
break;
case "MM":
return tf(date.getMonth() + 1);
break;
case "mm":
return tf(date.getMinutes());
break;
case "dd":
return tf(date.getDate());
break;
case "HH":
return tf(date.getHours());
break;
case "ss":
return tf(date.getSeconds());
break;
}
});
},
/**
* 获取指定日期星期几
*/
getWeekday: function (dateStr) {
if (typeof dateStr === "string") {
dateStr = dateStr.replace(/-/g, "/");
}
let date = dateStr ? new Date(dateStr) : new Date();
return ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"][
date.getDay()
];
},
/**
* 获取当前日期对象,主要信息
*/
getDateNowData: function () {
var date = new Date();
return {
date: date,
year: date.getYear(),
fullYear: date.getFullYear(),
month: date.getMonth() + 1,
day: date.getDate(),
weekday: [
"星期日",
"星期一",
"星期二",
"星期三",
"星期四",
"星期五",
"星期六"
][date.getDay()],
time: date.getTime(),
hours: date.getHours(),
minutes: date.getMinutes(),
seconds: date.getSeconds()
};
}
}
this.urlUtils = {
/**
* 将对象转为浏览器的url参数类型 key=value&key=value...
* @author pengliang
* @param obj
* @param prefix
* @returns {string}
*/
toSimpleUrlParameter: function (obj, prefix) {
var nullStr = '';
if (!obj) {
return nullStr;
}
var params = [];
for (var key in obj) {
var value = obj[key];
if (value && typeof value != 'object') {
params.push(key + '=' + value);
}
}
return params.length == 0 ? nullStr : (prefix === true ? '?' : '') + params.join("&");
},
/**
* 解析浏览器参数,如果name参数为空则返回解析后的所有参数,否则name匹配后的value
* @author pengliang
* @param name
* @return {null}
*/
getQueryParameter: function (name) {
var search = location.search.length > 0 ? location.search.substr(1) : '';
if (!search) return null;
var Query = {};
var value = null;
if (search.indexOf('&') >= 0) {
var strArray = search.split('&');
$.each(strArray, function (i, item) {
if (item.indexOf('=') >= 0) {
var arr = item.split('=');
var pName = decodeURIComponent(arr[0]);
var pValue = decodeURIComponent(arr[1]);
if (name && name == pName) {
value = pValue;
return false
} else {
Query[pName] = pValue;
}
}
});
} else {
if (search.indexOf("=") >= 0) {
var arr = search.split('=');
var pName = decodeURIComponent(arr[0]);
var pValue = decodeURIComponent(arr[1]);
if (name && name == pName) {
value = pValue;
} else {
Query[pName] = pValue;
}
}
}
return name ? value : Query;
}
}
var mathUtils = {
//加 console.log( 0.1 + 0.2 ); //输出 0.30000000000000004
floatAdd: function (arg1, arg2) {
var r1, r2, m;
try {
r1 = arg1.toString().split(".")[1].length;
} catch (e) {
r1 = 0;
}
try {
r2 = arg2.toString().split(".")[1].length;
} catch (e) {
r2 = 0;
}
m = Math.pow(10, Math.max(r1, r2));
return (arg1 * m + arg2 * m) / m;
},
//减 console.log( 1 - 0.8 ); //输出 0.19999999999999996
floatSub: function (arg1, arg2) {
var r1, r2, m, n;
try {
r1 = arg1.toString().split(".")[1].length;
} catch (e) {
r1 = 0;
}
try {
r2 = arg2.toString().split(".")[1].length;
} catch (e) {
r2 = 0;
}
m = Math.pow(10, Math.max(r1, r2));
//动态控制精度长度
n = r1 >= r2 ? r1 : r2;
return ((arg1 * m - arg2 * m) / m).toFixed(n);
}
//乘 console.log( 6 * 0.7 ); //输出 4.199999999999999
, floatMul: function (arg1, arg2) {
var m = 0,
s1 = arg1.toString(),
s2 = arg2.toString();
try {
m += s1.split(".")[1].length;
} catch (e) { }
try {
m += s2.split(".")[1].length;
} catch (e) { }
return (
(Number(s1.replace(".", "")) * Number(s2.replace(".", ""))) /
Math.pow(10, m)
);
}
//除 console.log( 1.2 / 0.2 ); //输出 5.999999999999999
, floatDiv: function (arg1, arg2) {
var t1 = 0,
t2 = 0,
r1,
r2;
try {
t1 = arg1.toString().split(".")[1].length;
} catch (e) { }
try {
t2 = arg2.toString().split(".")[1].length;
} catch (e) { }
r1 = Number(arg1.toString().replace(".", ""));
r2 = Number(arg2.toString().replace(".", ""));
return (r1 / r2) * Math.pow(10, t2 - t1);
}
}
}(jQuery);
Date.prototype.format = function (fmt) {
var o = {
"M+": this.getMonth() + 1, //月份
"d+": this.getDate(), //日
"h+": this.getHours(), //小时
"m+": this.getMinutes(), //分
"s+": this.getSeconds(), //秒
"q+": Math.floor((this.getMonth() + 3) / 3), //季度
"S": this.getMilliseconds() //毫秒
};
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (this.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;
}
上一篇: 作为媳妇如何处理婆媳关系?
下一篇: 老公在家就是个大爷