整理日常开发中我们常常会使用到的一些工具函数。

var utils = (function(){
var fay = {}; // 返回当前时间的毫秒数
fay.getTime = Date.now()
|| function getTime() {return new Date().getTime();}; // 对象复制
fay.extend = function(target, obj) {
if(obj && typeof obj !== 'object') return throw new Error(obj + 'is not object');
for(var i in obj) {
if(obj.hasOwnProperty(i)) {
target[i] = obj[i];
}
}
}; /*
* 获取 url 的参数
*/
fay.getUrlParams = function (url) {
var url = url || location.search,
params = {},
route = '';
if(url) {
route = url.split("?")[1].split("&");
route.forEach(function (item) {
var item = item.split("=");
if(item) {
params[item[0]] = item[1].replace(/(.*)([.|\#]$)/,"$1");
}
})
}else {
console.log('未找到参数!')
}
return params;
}; // 设置cookies
fay.setCookie = function (name, value, time) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + time);
document.cookie = name + "=" + encodeURIComponent(value)
+ ((time == null) ? "" : ";expires=" + exdate.toUTCString())+";path=/";
}; // 读取cookies
fay.getCookie = function (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 decodeURIComponent(document.cookie.substring(c_start,c_end))
}
}
return ""
}; // 删除cookies
fay.delCookie = function (name) {
var exp = new Date();
exp.setTime(exp.getTime() - 1);
var cookieval = this.getCookie(name);
if(cookieval)
document.cookie = name +"="+ cookieval +";expires=" + exp.toUTCString();
}; /**
* mergeArr 合并含有相同value对象元素的数组
* @param {Array} arr 数组
* @param {String} key 字段
* @return {Object}
*
* @example
* var arr = [{m:1,n:22}, {m:1,x:54}, {m:5,e:29},{m:5,k:9}]
* this.mergeArr(arr, 'm')
* {
* 1:[{m:1,n:22},{m:1,x:54}],
* 5:[{m:5,e:29},{m:5,k:9}]
* }
*/
fay.mergeArr = function (arr, key) {
var obj = {};
arr.forEach(function (item, index, arr) {
var m = item[key];
if(!obj[m]) {
obj[m] = [item];
}else {
[].push.call(obj[m],item);
}
});
return obj;
}; /**
* mergeArr 合并含有相同value对象元素的数组
* @param {Array} arr 数组
* @return {Object}
*
* @example
* var arr = [{1:2,8:0,3:5},{1:0,8:8,3:51}]
* this.mergeArr(arr)
* {
* {1:[2,0],3:[5,51],8:[0,8]}
* }
*/
fay.mergeArrByKey = function(arr) {
var obj = {},
result = [],
key;
arr.forEach(function (item, index, arr) {
for(key in item) {
if(!obj[key]){
obj[key] = [];
obj[key].push(item[key])
}else{
obj[key].push(item[key])
}
} });
for(var i in obj) {
result.push(obj[i])
}
return result;
}; /**
* by 对象数组排序
*
*/
fay.sortBy = function (name) {
return function (o, p) {
var a, b;
if (typeof o === "object" && typeof p === "object" && o && p) {
a = o[name];
b = p[name];
if (a === b) {
return 0;
}
if (typeof a === typeof b) {
return a < b ? -1 : 1;
}
return typeof a < typeof b ? -1 : 1;
}
else {
throw ("error");
}
}
}; /**
* 将时间戳转化为标准时间格式
*
* */
fay.switchTimestamp = function (timestamp, newStandard) {
// 设置需要的时间格式
var newStandard = newStandard || '$2月$3日';
var newDate = new Date();
var standardTime = "",
fullYear='',month = '', day='',
arr = [];
function getArr(newDate) {
fullYear = newDate.getFullYear();
month = newDate.getMonth()+1;
day = newDate.getDate();
arr.push(fullYear);
arr.push(month);
arr.push(day);
if(arr[1] < 10) {
arr[1] = '0'+arr[1]
}
if(arr[2] < 10) arr[2] = '0'+arr[2];
standardTime = arr.join('/');
return standardTime;
}
if(/^\d{13}$/.test(timestamp)) {
newDate.setTime(timestamp);
standardTime = getArr(newDate);
}else if(/^\d{16}$/.test(timestamp)) {
newDate.setTime(timeStamp / 1000);
standardTime = getArr(newDate);
} else {
console.error("时间戳格式不正确");
}
// 返回需要的时间格式
return standardTime.replace(/^(\d{4})\/(\d{1,2})\/(\d{1,2})$/, newStandard);
}; /*
* 将日期字符串转为时间戳
* @param {Date} date(天) "0-31"
* return 1484733218000
*/
fay.toTimeStamp = function (date) {
if(date) {
var d = new Date();
d.setDate(d.getDate() + date);
return d;
}else {
return Date.parse(new Date());
}
}; // 长按事件
fay.longPress = function (ele, cb, clickCb) {
var timeOut = 0;
ele.on({
touchstart: function (e) {
var objTarget = e.target ? e.target : e.srcElement;
console.log($(this).find(".panel_info").attr("data-id"));
timeOut = setTimeout(function () {
var name = prompt("请修改礼品单",'');
}, 500);
return false;
},
touchmove: function (e) {
clearTimeout(timeOut);
timeOut = 0;
return false;
},
touchend: function (e) {
clearTimeout(timeOut);
if(timeOut) {
clickCb;
}
return false;
}
})
};
fay.throttle = function(method, context, delay) {
var delayTime = delay || 1000;
clearTimeout(context.tId);
context.tId = setTimeout(function(){
method.call(context);
}, delayTime);
}; return fay;
})()
function ease(x) {
return Math.sqrt(1 - Math.pow(x - 1, 2));
} function reverseEase(y) {
return 1 - Math.sqrt(1 - y * y);
}

javascript 实用工具函数的更多相关文章

  1. JQuery实践--实用工具函数

    实用工具函数,$命名空间的一系列函数,但不操作包装集.它要么操作除DOM元素以外的Javascript对象,要么执行一些非对象相关的操作. JQuery的浏览器检测标志可在任何就绪处理程序执行之前使用 ...

  2. Lodash JavaScript 实用工具库

    地址:https://www.lodashjs.com/ Lodash 是一个一致性.模块化.高性能的 JavaScript 实用工具库.

  3. jQuery实用工具函数

    1. 什么是工具函数 在jQuery中,工具函数是指直接依附于jQuery对象.针对jquery对象本身定义的说法,即全局性的函数,我们统称为工具函数,或Utilities函数.它们有一个明显的特征, ...

  4. 读<jQuery 权威指南>[6]--实用工具函数

    官方地址:http://api.jquery.com/category/utilities/ 一.数组和对象操作 1. $.each——遍历 $.each(obj,function(param1,pa ...

  5. javascript常用工具函数总结(不定期补充)未指定标题的文章

    前言 以下代码来自:自己写的.工作项目框架上用到的.其他框架源码上的.网上看到的. 主要是作为工具函数,服务于框架业务,自身不依赖于其他框架类库,部分使用到es6/es7的语法使用时要注意转码 虽然尽 ...

  6. 你要的几个JS实用工具函数(持续更新)

    今天,我们来总结下我们平常使用的工具函数,希望对大家有用.1.封装fetch 源码: /** * 封装fetch函数,用Promise做回调 * @type {{get: (function(*=)) ...

  7. JavaScript常用工具函数

    检测数据是不是除了symbol外的原始数据 function isStatic(value) { return ( typeof value === 'string' || typeof value ...

  8. JavaScript 设计模式 - 工具函数

    1.类式继承,模拟面向对象语言的继承方式 function extend(subClass, superClass) { var F = function() {}; F.prototype = su ...

  9. JavaScript 实用工具库 : lodashjs

    首页地址:https://www.lodashjs.com/

随机推荐

  1. 那些你不知道的PS大片摄影

    你以为这张照片是P出来的? 才不是! 人家是开个起重机吊着拍的! 而且没有任何保护措施! 这样的照片战斗民族的摄影师才敢这样拍…要是在天朝这么做估计都找不到模特… 这张照片出自乌兹别克斯坦的摄影师Ra ...

  2. IPEndPoint

    .NET框架用IPEndPoint 对象来表示一个特定的IP地址和端口的组合,应用该对象的场景多是在讲socket绑定到本地地址或者将socket绑定到非本地地址.

  3. vue.js项目打包上线

    最近一直坚持每个月写一个小的vue.js 开发的项目,最后开发完成后想到很久之前给别人回答的一个问题:vue的项目如何上线,当时有千奇百怪的回答,我在想,这些人都是肿了么,vue的官方都说了,这个框架 ...

  4. http mimetype为multipart/x-mixed-replace报文

    http://blog.csdn.net/gmstart/article/details/7064034 服务器推送(Server Push) 推送技术的基础思想是将浏览器主动查询信息改为服务器主动发 ...

  5. 十年前,女:“对不起,我不会喜欢你的,你不要再坚持了,就好比让 Linux 和 Windows 同时运行在一台PC机上,可能吗?

    1.十年前,女:“对不起,我不会喜欢你的,你不要再坚持了,就好比让 Linux 和 Windows 同时运行在一台PC机上,可能吗?”男生听后默默走开, 十年后,在一次虚拟技术大会上,我听到一名虚拟技 ...

  6. 2018.09.05 任务安排(斜率优化dp)

    描述 这道题目说的是,给出了n项必须按照顺序完成的任务,每项任务有它需要占用机器的时间和价值.现在我们有一台机器可以使用,它每次可以完成一批任务,完成这批任务所需的时间为一个启动机器的时间S加上所有任 ...

  7. java.lang.NoClassDefFoundError Could not initialize class 异常的处理

    class,forname的配置文件出问题核对url数据库中的名字和bean中名字不同没有把jar包变成build path

  8. Python之Pandas中Series、DataFrame

    Python之Pandas中Series.DataFrame实践 1. pandas的数据结构Series 1.1 Series是一种类似于一维数组的对象,它由一组数据(各种NumPy数据类型)以及一 ...

  9. (线段树)Balanced Lineup --POJ --3264

    链接: 对于POJ老是爆,我也是醉了, 链接等等再发吧! http://acm.hust.edu.cn/vjudge/contest/view.action?cid=82832#problem/G 只 ...

  10. hdu3853 LOOPS(概率dp) 2016-05-26 17:37 89人阅读 评论(0) 收藏

    LOOPS Time Limit: 15000/5000 MS (Java/Others)    Memory Limit: 125536/65536 K (Java/Others) Total Su ...