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

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. redis缓存设置和读取

    一/写入 <?php $redis = new Redis(); //实例化redis $redis->pconnect('); $redis->,'huahua'); //设置变量 ...

  2. composer install 时,提示:Package yiisoft/yii2-codeception is abandoned, you should avoid using it. Use codeception/codeception instead.的解决

    由 SHUIJINGWAN · 2017/11/24 1.composer install 时,提示:Package yiisoft/yii2-codeception is abandoned, yo ...

  3. 11 Maven 灵活的构建

    Maven 灵活的构建 一个优秀的构建系统必须足够灵活,它应该能够让项目在不同的环境下都能成功地构建.例如,典型的项目都会有开发环境.测试环境和产品环境,这些环境的数据库配置不尽相同,那么项目构建的时 ...

  4. 调用数据库--stone

    from Mysql_operate_class import mysql def saveMysqlData(sql, dbname="algorithm"): pym = my ...

  5. 最近学习工作流 推荐一个activiti 的教程文档

    全文地址:http://www.mossle.com/docs/activiti/ Activiti 5.15 用户手册 Table of Contents 1. 简介 协议 下载 源码 必要的软件 ...

  6. CSS 关键的基础知识

    今晚看了 百度传课 一门关于CSS的课程, 感觉不错, 随手记了点儿笔记, 供以后查阅. =================================================== pos ...

  7. java最全的Connection is read-only. Queries leading to data modification are not allowed

    Connection is read-only. Queries leading to data modification are not allowed 描述:框架注入时候,配置了事物管理,权限设置 ...

  8. HDU 5618 Jam's problem again (cdq分治+BIT 或 树状数组套Treap)

    题意:给n个点,求每一个点的满足 x y z 都小于等于它的其他点的个数. 析:三维的,第一维直接排序就好按下标来,第二维按值来,第三维用数状数组维即可. 代码如下: cdq 分治: #pragma ...

  9. 记一次web服务模块开发过程

    一.前言 之前在分析WCS系统的过程中,也赶上要开发其中的一个模块,用于和AGV系统对接完成一些取货.配盘等任务:在这里将这次模块开发的全过程记录一下,以便自己以后开发时能够更加快速的明白流程. 二. ...

  10. AE IRasterCursor 获取栅格图层像素值

    在编写使用栅格图层的代码时,常常要获取栅格图层的像素值(PixelValue).如果想获取某一点的像素值,可以使用IRaster2中的getPixelValue方法.但如果想要获得的是图层中的某一块甚 ...