javascript常用工具函数总结(不定期补充)未指定标题的文章
前言
以下代码来自:自己写的、工作项目框架上用到的、其他框架源码上的、网上看到的。
主要是作为工具函数,服务于框架业务,自身不依赖于其他框架类库,部分使用到es6/es7的语法使用时要注意转码
虽然尽量在函数中做了错误情况的处理,仍有可能出现报错的情况(不定期完善)
1. 获取url上的参数
/**
*获取url上的参数
* @return {object}
* @example
* getRequest() getRequest().paramA
*/
function getRequest() {
var searchString = window.location.search.substring(1),
params = searchString.split("&"),
hash = {};
if (searchString == "") return {};
for (var i = 0; i < params.length; i++) {
var pos = params[i].indexOf('=');
if (pos == -1) { continue; }
var paraName = params[i].substring(0, pos),
paraValue = params[i].substring(pos + 1);
hash[paraName] = paraValue;
}
return hash;
}
返回一个对象,将url上的参数以键值对的形式存储在返回结果中,如果url上没参数,则返回空对象
2. 计算两个日期的时间差
/**
* 计算两个日期时间的时间差
* @param {Date, Date} date1 date2
* @return {object | null}
* @example
* getDiff(new Date('2017-09-08'), new Date())
*/
function getDiff(date1, date2) {
if (!date1.getTime || !date2.getTime) return null
var ms = (date1.getTime() - date2.getTime());
var day1 = Math.round(ms / 24 / 3600 / 1000),
hh1 = Math.round((ms / 3600 / 1000) % 24),
mm1 = Math.round((ms / 1000 / 60) % 60),
ss1 = Math.round((ms / 1000) % 60);
return {
day: day1,
hour: hh1,
minute: mm1,
second: ss1
};
}
传入两个Date日期对象,返回一个对象,其属性值day、hour、minute、second分别表示相差天数、小时、分钟、秒。结果以Math.round()取整,如果结果为负,则表示第一个日期在第二个日期前面
3. 将canvas转化为image图片格式
/**
* 将canvas转化为image格式
* @param {string} cId
* @return {object HTMLImageElement}
* @example
* canvasToImg('canvas') canvasToImg('#canvarsId')
*/
function canvasToImg(cId){
let canvas = document.querySelector(cId)
if (!canvas || !canvas.toDataURL) return new Image()
let imgData = canvas.toDataURL('image/png'),
imgs= new Image();
imgs.src=imgData;
return imgs
}
传入一个css选择器,函数根据选择器查询canvas节点,然后返回该canvas的image格式节点,如果查找不到则返回一个空的image。原理是将canvas转化为base64编码,toDataURL方法貌似是canvas节点独有的,然后新建一个src是这个base64编码的图片。
ps:什么情况下需要做这种转换呢?目前我知道的一个就是canvas在移动端无法长按保存到手机。
4. 生成随机guid
/**
* 生成一个唯一的guid
* @return {string}
* @example
* // 7f603b20-17ff-4f47-aeb9-e7996de04939
* util.guid();
* @see http://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript
*/
function guid () {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
}
这个方法用于生成一个随机guid,可以将生成的guid视为全局唯一的(生成两个相同id的情况很少)。guid似乎在前端用的比较少,目前项目用到就是在每次请求后端接口时调用此方法,生成一个guid传过去。
5. 获取一个月份的天数
function isLeapYear (year) {
if (year % 100 === 0) {
if (year % 400 === 0) {
return true;
}
} else if (year % 4 === 0) {
return true;
}
return false;
}
/**
* 获取某个月份有多少天
* @return {number}
* @param {string | number} year month
* @example
* getDaysInMonth(2017, 9)
*/
function getDaysInMonth (year, month) {
return [31, isLeapYear(year) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
}
传入一个年份和月份,返回该月有多少天,其中也包含了一个isLeapYear方法来判断是否是闰年,应该在实现日历或者日期选择组件时用的到
结语
暂时就写这么多了,后面不定期补充。
javascript常用工具函数总结(不定期补充)未指定标题的文章的更多相关文章
- JavaScript常用工具函数
检测数据是不是除了symbol外的原始数据 function isStatic(value) { return ( typeof value === 'string' || typeof value ...
- javascript常用工具类整理(copy)
JavaScript常用工具类 类型 日期 数组 字符串 数字 网络请求 节点 存储 其他 1.类型 isString (o) { //是否字符串 return Object.prototype.to ...
- vue项目工具文件utils.js javascript常用工具类,javascript常用工具类,util.js
vue项目工具文件utils.js :https://blog.csdn.net/Ajaxguan/article/details/79924249 javascript常用工具类,util.js : ...
- numpy 常用工具函数 —— np.bincount/np.average
numpy 常用工具函数 —— np.bincount/np.average numpy 常用api(一) numpy 常用api(二) 一个函数提供 random_state 的关键字参数(keyw ...
- JavaScript常用工具方法
JavaScript常用工具方法 1.日期格式化 2.将日期字符串转换为Date,字符串格式为(yyyy-mm-dd hh:mm:ss) 3.JS获取当天00:00:00时间和23:59:59的时间 ...
- javascript 实用工具函数
整理日常开发中我们常常会使用到的一些工具函数. var utils = (function(){ var fay = {}; // 返回当前时间的毫秒数 fay.getTime = Date.now( ...
- javascript常用字符串函数和本地存储
concat将两个或多个字符的文本组合起来,返回一个新的字符串.var a = "hello";var b = ",world";var c = a.conca ...
- javaScript常用工具库
对应于百度前端技术学院2015年春季的课程2相关内容 https://github.com/baidu-ife/ife/tree/master/2015_spring/task/task0002 ht ...
- JS开发常用工具函数 总结
js原生工具库 1.isStatic:检测数据是不是除了symbol外的原始数据 */ function isStatic(value) { return( typeof value === 'str ...
随机推荐
- 吴裕雄--天生自然python机器学习:KNN-近邻算法在手写识别系统上的应用
需要识别的数字已经使用图形处理软件,处理成具有相同的色 彩和大小® : 宽髙是32像 素 *32像素的黑白图像.尽管采用文本格式存储图像不能有效地利用内 存空间,但是为了方便理解,我们还是将图像转换为 ...
- Mysql 和 Java对比异同
1.求两个时间的差(天数) mysql : to_days 距离公元0年的天数 select TO_DAYS('2017-10-18 00:00:00'),TO_DAYS(NOW()), (TO_DA ...
- jQuery实现button按钮提交表单
在JSP页面中,通常使用button按钮提交表单数据,使用jQuery实现代码如下: <span style="font-family:Comic Sans MS;font-size: ...
- Introduction to Computer Science and Programming in Python--MIT
学习总结--(Introduction to Computer Science and Programming in Python--MIT) 导论 主题 重新利用数据结构来表达知识 理解算法的复杂性 ...
- [LC] 300. Longest Increasing Subsequence
Given an unsorted array of integers, find the length of longest increasing subsequence. Example: Inp ...
- 如何用Nginx解决跨域问题
一. 产生跨域的原因 1.浏览器限制 2.跨域 3.XHR(XMLHttpRequest)请求 二. 解决思路 解决跨域有多重,在这里主要讲用nginx解决跨域 1.JSONP 2.nginx代理 3 ...
- Pivotal tc Server Integration for Eclipse
Pivotal tc Server Integration for Eclipse
- Pycharm 2019 破解激活方法
转载:https://blog.csdn.net/guofang110/article/details/87793264 使用破解补丁方法虽然麻烦,但是可用激活到2099年,基本上是永久激活了,毕竟在 ...
- mybatis 添加后获得该新增数据自动生成的 id
// useGeneratedKeys默认值为false,keyProperty的值对应的是User类中的主键字段名 // mybatis 写法如下 <insert id="inser ...
- http://yuedu.baidu.com/ebook/36edd3d7ba1aa8114531d911
本书概述: 全面深入自动化测试技术,包括接口自动化测试.app自动化测试.性能自动化测试技术:实践,理论结合,方案,环境,代码 java语言,python语言,自动化测试开发 ...