JS 工具类
之前工作用的JavaScript比较多,总结了一下工具类,和大家分享一下,有不足之处还请多多见谅!!
1. 数组工具类(arrayUtils)
var arrayUtils = {};
(function (object) {
//arguments parameter
object.concat = function (arr) {
if (arguments.length > 0) {
for (i = 1;i < arguments.length; i++) {
arr=arr.concat(arguments[i]);
}
}
return arr;
};
object.join = function (arr,separator) {
return arr.join(separator);
};
object.push = function (arr) {
if (arguments.length > 0) {
for (i = 1;i < arguments.length; i++) {
arr.push(arguments[i]);
}
}
return arr;
};
object.slice = function (arr,start,end) {
return arr.slice(start,end);
};
object.sort = function (arr,isDesc) {
if(isDesc){
arr.sort(function (a,b) {
return a<b?1:-1;
});
}else{
arr.sort(function (a,b) {
return a<b?-1:1;
});
}
return arr;
};
object.unshift = function (arr) {
if (arguments.length > 0) {
for (i = 1;i < arguments.length; i++) {
arr.unshift(arguments[i]);
}
}
return arr;
};
object.inArray=function (arr,targetValue) {
var hasTargetValue=false;
$.each(arr,function (index,item) {
if(item==targetValue){
hasTargetValue=true;
}
});
return hasTargetValue;
};
//差集
object.except=function (sourceArray,targetArray) {
var self=this;
var exceptArray=[];
$.each(sourceArray,function (index,item) {
if(!self.inArray(targetArray,item)){
exceptArray.push(item);
}
});
$.each(targetArray,function (index,item) {
if(!self.inArray(sourceArray,item)){
exceptArray.push(item);
}
});
return exceptArray;
};
//交集
object.intersect=function (sourceArray,targetArray) {
var self=this;
var intersectArray=[];
$.each(sourceArray,function (index,item) {
if(self.inArray(targetArray,item)){
intersectArray.push(item);
}
});
return intersectArray;
};
})(arrayUtils); 2.Cookie工具类(cookieUtils)
var cookieUtils={};
(function (object) {
object.setCookie=function (key,value,expires) {
$.cookie(key, JSON.stringify(data), { expires: expires, path: '/' });
};
object.getCookie=function (key) {
return $.cookie(key);
};
object.getServerCookie=function (cookieName,key) {
var cookieValue = $.cookie(cookieName);
var cookieItems = cookieValue.split('&');
var itemValue = '';
$.each(cookieItems, function (index, item) {
if (item.indexOf(key) > -1) {
itemValue = item.match(/=.*/g)[0].replace(/=/, '');
}
});
return itemValue;
};
object.clearCookie=function (key,expires) {
$.cookie(key, null, { expires: expires, path: '/' });
};
})(cookieUtils); 3.日期工具类(dateTimeUtils)
/**
* Created by JerryChen on 2016/12/30.
*/
var dateTimeUtils = {};
(function (object) {
object.now = function () {
return new Date();
};
object.toString = function (value, format) {
var returnValue = '';
var placeHolder = '00';
var separator = '';
var formatArray = ['y', 'M', 'd', 'h', 'm', 's'];
var yearFormat = format.match(/y+/g);
var formatLength = 0;
var isContains = false;
if (yearFormat != null && yearFormat[0].length <= 4) {
formatLength += yearFormat[0].length;
var yearValue = value.getFullYear().toString();
separator = format.substr(formatLength, 1);
isContains = inArray(formatArray, separator);
if (isContains) {
separator = "";
} else {
formatLength += 1;
}
returnValue += yearValue.substr(4 - yearFormat[0].length, yearFormat[0].length) + separator;
}
var monthFormat = format.match(/M+/g);
if (monthFormat != null && monthFormat[0].length <= 2) {
formatLength += monthFormat[0].length;
var monthValue = (value.getMonth() + 1).toString();
separator = format.substr(formatLength, 1);
isContains = inArray(formatArray, separator);
if (isContains) {
separator = "";
} else {
formatLength += 1;
}
returnValue += placeHolder.substr(0, 2 - monthFormat[0].length) + monthValue + separator;
}
var dayFormat = format.match(/d+/g);
if (dayFormat != null && dayFormat[0].length <= 2) {
formatLength += dayFormat[0].length;
var dayValue = value.getDate().toString();
separator = format.substr(formatLength, 1);
isContains = inArray(formatArray, separator);
if (isContains) {
separator = " ";
} else {
formatLength += 1;
}
returnValue += placeHolder.substr(0, 2 - dayFormat[0].length) + dayValue + separator;
}
var hourFormat = format.match(/h+/g);
if (hourFormat != null && hourFormat[0].length <= 2) {
formatLength += hourFormat[0].length;
var hourValue = value.getHours().toString();
separator = format.substr(formatLength, 1);
isContains = inArray(formatArray, separator);
if (isContains) {
separator = "";
} else {
formatLength += 1;
}
returnValue += placeHolder.substr(0, 2 - hourFormat[0].length) + hourValue + separator;
}
var minutesFormat = format.match(/m+/g);
if (minutesFormat != null && minutesFormat[0].length <= 2) {
formatLength += minutesFormat[0].length;
var minutesValue = value.getMinutes().toString();
separator = format.substr(formatLength, 1);
isContains = inArray(formatArray, separator);
if (isContains) {
separator = "";
} else {
formatLength += 1;
}
returnValue += placeHolder.substr(0, 2 - minutesFormat[0].length) + minutesValue + separator;
}
secondsFormat = format.match(/s+/g);
if (secondsFormat != null && secondsFormat[0].length <= 2) {
var secondsValue = value.getSeconds();
returnValue += placeHolder.substr(0, 2 - secondsFormat[0].length) + secondsValue;
}
return returnValue;
};
function inArray(array, targetValue) {
var flag = false;
$.each(array, function (index, item) {
if (targetValue == item) {
flag = true;
}
});
return flag;
}
object.dateDiff = function (startDate, endDate, format) {
if (format == "dd") {
return (endDate.getTime()-startDate.getTime())/86400000;
} else if (format == "hh") {
return Math.ceil((endDate.getTime()-startDate.getTime())/3600000);
} else if (format == "mm") {
return Math.ceil((endDate.getTime()-startDate.getTime())/60000);
} else if (format == "ss") {
return Math.ceil((endDate.getTime()-startDate.getTime())/1000);
}
};
object.addDays = function (value, days) {
return new Date(value.getTime() + days * 86400000);
};
object.addHours = function (value, hours) {
return new Date(value.getTime() + hours * 3600000);
};
object.addMinutes = function (value, minutes) {
return new Date(value.getTime() + minutes * 60000);
};
object.addSeconds = function (value, seconds) {
return new Date(value.getTime() + seconds * 1000);
};
})(dateTimeUtils); 4.枚举工具类(enumUtils)
/**
* Created by JerryChen on 2016/12/31.
*/
var enumUtils={};
(function (object) {
object.getEnumValue=function (enumSource,key) {
return enumSource[key];
};
object.getEnumData=function (enumSource) {
var data=[];
for (item in enumSource){
data.push({"Key":item,"Value":enumSource[item]})
}
return data;
}; })(enumUtils); 5.Json工具类(jsonUtils)
/**
* Created by JerryChen on 2016/12/31.
*/
var jsonUtils={};
(function (object) {
object.grepJsonArray=function (dataSource,filterRule) {
//var defaultRule=[{"FilterField":"","Value":"","Operator":""}];
if(filterRule!=undefined&&filterRule!=null&&filterRule.length>0){
$.each(filterRule,function (index,item) {
if (item.Operator=="="){
dataSource= $.grep(dataSource, function (item, index) {
return item.FilterField == item.Value;
}, false);
}
if (item.Operator=="!="){
dataSource= $.grep(dataSource, function (item, index) {
return item.FilterField != item.Value;
}, false);
}
});
}
return dataSource;
};
/**
* @return {boolean}
*/
object.isNotNullOrEmpty=function (dataSource) {
return dataSource!=undefined&&dataSource!=null&&dataSource.length>0; };
object.isNotEmptyObject=function (dataSource) {
return !$.isEmptyObject(dataSource);
};
object.getObjectProperty=function (dataSource,propertyName) {
return dataSource[propertyName];
};
object.removeObjectProperty=function (dataSource,propertyName) {
delete dataSource[propertyName];
return dataSource;
} })(jsonUtils); 6.Mapper工具类(mapperUtils)
/**
* Created by JerryChen on 2016/12/31.
*/
var mapperUtils={};
(function (object) {
object.extend=function (dataSource,dataTarget) {
$.extend(true,dataTarget,dataSource);
return dataTarget;
};
})(mapperUtils); 7.Number工具类(numberUtils)
/**
* Created by JerryChen on 2016/12/30.
*/
var numberUtils = {};
(function (object) {
object.isNumber = function (value) {
if (/\d+/.test(value)) {
return true;
}
return false;
};
object.toInt = function (value) {
if (this.isNumber(value)) {
return parseInt(value);
} else {
return value;
}
};
object.toDouble = function (value, number) {
return value.toFixed(number);
};
object.toFloat = function (value) {
return parseFloat(value);
};
object.max = function () {
var maxValue;
if (arguments.length > 0) {
if (arguments.length == 1) {
arguments[0].sort(function (a, b) {
return a > b ? -1 : 1;
});
maxValue = arguments[0][0];
} else {
var arr=[];
for(i=0;i<arguments.length;i++){
arr.push(arguments[i]);
}
arr.sort(function (a, b) {
return a > b ? -1 : 1;
});
maxValue = arr[0];
}
}
return maxValue;
};
object.min = function () {
var minValue;
if (arguments.length > 0) {
if (arguments.length == 1) {
arguments[0].sort(function (a, b) {
return a > b ? 1 : -1;
});
minValue = arguments[0][0];
} else {
var arr=[];
for(i=0;i<arguments.length;i++){
arr.push(arguments[0]);
}
arr.sort(function (a, b) {
return a > b ? 1 : -1;
});
maxValue = arr[0];
}
}
return minValue;
}
})(numberUtils); 8.String工具类(stringUtils)
/**
* Created by JerryChen on 2016/12/30.
*/
var stringUtils={};
(function (object) {
object.subString=function (value,start,length) {
return value.substr(start,length);
};
object.truncate=function (value,maxLength,suffix) {
if(value!=undefined&&value.length>maxLength){
value=value.substr(0,maxLength)+suffix;
}
return value;
};
object.length=function (value) {
if(value!=undefined){
return value.length;
}else {
return 0;
}
};
object.endTrim=function (value) {
if(value!=undefined){
value=value.substr(0,value.length-1);
}
return value;
};
object.isNotNull=function (value) {
return value!=undefined&&value!=null;
};
object.isNotNullOrEmpty=function (value) {
return value!=undefined&&value!=null&&value!="";
};
object.isEqual=function (value,compareWith) {
return value==compareWith;
};
object.indexOf=function (value,targetValue) {
return value.indexOf(targetValue);
}
})(stringUtils); 9.Url工具类(urlUtils)
/**
* Created by JerryChen on 2016/12/31.
*/
var urlUtils={};
(function (object) {
object.getParam= function (search,paramName) {
var reg = new RegExp("(^|&)" + paramName + "=([^&]*)(&|$)");
var result = search.substr(1).match(reg);
if (result != null) {
return decodeURIComponent(result[2]);
} else {
return undefined;
}
};
object.getHost=function () {
return window.location.host;
}
})(urlUtils); 10.StringBuilder
function StringBuilder() {
this._string = new Array();
};
StringBuilder.prototype.append = function (str) {
this._string.push(str);
return this;
};
StringBuilder.prototype.appendLine = function (str) {
this._string.push(str + "\n");
return this;
};
StringBuilder.prototype.appendFormat = function (value) {
for (var i = 1; i < arguments.length; i++) {
var placeHolder = "\\{" + (i - 1) + "\\}";
var reg = new RegExp(placeHolder, "g");
value = value.replace(reg, arguments[i]);
}
this._string.push(value);
return this;
};
StringBuilder.prototype.toString = function () {
return this._string.join("");
}
github地址:https://github.com/jerrychen0705/JS.Utilities
JS 工具类的更多相关文章
- 分享非常好用的前端分页js工具类 灵活 简单易懂
分享自己封装的前端分页js工具类 下面是默认样式效果截图 可以随意更改js及css 很灵活 /** * pageSize, 每页显示数 * pageIndex, 当前页数 * pageCount 总 ...
- Rhino+envjs-1.2.js 在java运行网站js 工具类
java爬虫遇到个页面加密的东西,找了些资料学习学习 做了个java运行js的工具类,希望对大家有用,其中用到client(获取js)可以自行换成自己的client.主要是用了 Rhino就是Java ...
- js工具类的封装
common.js原生js实现的大多工具方法都将放在common文件中 布局rem.js,vue开发时,我们只需要将rem.js再main.js中import 引入即可 (function(win, ...
- 一些通用的js工具类,添加自定义插件
common_t.js /** * 通用工具组件 对原有的工具进行封装,自定义某方法统一处理<br> * ^_^ * * Author: em.D * Date: 2016-05-17 * ...
- js工具类大全
/********** 日期处理函数 *********/<script type="text/javascript" src="${springMacroRequ ...
- js工具类 ----正则
function(value){ if(value){ var reg=new RegExp("^[a-zA-Z0-9_-]+$"); return reg.test(v ...
- JS工具类
封装了开发中常用的操作 并添加了一些扩展方法供调用 var util = { //获取Url中的参数(不支持中文) getParams: function() { var url = location ...
- html传参数 js工具类
var QueryUtils = { GetQueryString: function (name) { var reg = new RegExp("(^|&)" + na ...
- js 时间戳转yyyy-MM-dd HH-mm-ss工具类
转载自:https://blog.csdn.net/shan1774965666/article/details/55049819 在web开发中,我们经常需要用js将时间戳转yyyy-MM-dd H ...
随机推荐
- ckplayer 如何在PC上完美支持 m3u8播放
使用过ckplayer的同学都知道,相对jwplayer等,它非常的容易配置和使用.功能也是基本满足我们的需求的. 一般情况我们都使用普通的视频格式比如mp4,flv等播放,但如果视频文件过大,会加载 ...
- 从配置读取一段时间(TimeSpan)
C#的TimeSpan表示一段时间,DateTime表示一个时间点.TimeSpan可正可负,可与DateTime相加减,很方便,我喜欢. 代码中我们经常要表示一段时间,用一个统一的单位(时 或者 分 ...
- memcached安装配置+基础操作
先安装依赖关系 下载libevent-2.0.21-stable.tar.gz wget https://github.com/downloads/libevent/libevent/libevent ...
- 如何在github上下载单个文件夹?
作者:ce ge链接:https://www.zhihu.com/question/25369412/answer/96174755来源:知乎著作权归作者所有,转载请联系作者获得授权. Git1.7. ...
- [iOS]技巧集锦:UICollectionView在旋转屏幕后Cell中的约束不起作用或自动布局失效
这似乎是iOS的一个BUG(ref: stackoverflow的大神们讲的) 解决方案 在继承自UITableViewCell的子类中的init方法中加入如下设置: self.contentView ...
- Mybatis
Mybatis MyBatis本是apache的一个开源项目iBatis,2010年这个项目有Apache software foundation 迁移到了Google code,并改名MyBatis ...
- LZ77.py
import math from bitarray import bitarray class LZ77Compressor: """ A simplified impl ...
- [LeetCode] Strobogrammatic Number 对称数
A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside ...
- [LeetCode] Consecutive Numbers 连续的数字
Write a SQL query to find all numbers that appear at least three times consecutively. +----+-----+ | ...
- 从随机过程到马尔科夫链蒙特卡洛方法(MCMC)
从随机过程到马尔科夫链蒙特卡洛方法 1. Introduction 第一次接触到 Markov Chain Monte Carlo (MCMC) 是在 theano 的 deep learning t ...