1.JS判断是否为空
/**
* JS判断是否为空
* @param val
* @returns {boolean}
*/
function isNull(val) {
if (val == undefined || val == null || val == "" || val == ''
|| val == "undefined" || val == "null" || val == "NULL") {
return true;
}
return false;
}
2.JS时间戳转成时间
timeStamp2String(1526552438244); // 2018-05-17 18:20:38
/**
* JS时间戳转成时间
* @param time
* @returns
*/
function timeStamp2String(time){
var datetime = new Date();
datetime.setTime(time);
var year = datetime.getFullYear();
var month = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
var date = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();
var hour = datetime.getHours()< 10 ? "0" + datetime.getHours() : datetime.getHours();
var minute = datetime.getMinutes()< 10 ? "0" + datetime.getMinutes() : datetime.getMinutes();
var second = datetime.getSeconds()< 10 ? "0" + datetime.getSeconds() : datetime.getSeconds();
return year + "-" + month + "-" + date+" "+hour+":"+minute+":"+second;
}
3.JS时间戳转成时间(通用版,可以自定义格式)
/**
* JS时间戳转成时间
* @param time
* @returns
*/
function formatDate(timestamp, formats){
formats = formats || 'Y-M-D';
var myDate = undefined;
if (timestamp) {
if (typeof(timestamp) != 'string') {
myDate = timestamp;
}
else {
myDate = new Date(timestamp);
}
}
else {
myDate = new Date();
}
var year = myDate.getFullYear();
var month = formatDigit(myDate.getMonth() + 1);
var day = formatDigit(myDate.getDate());
var hour = formatDigit(myDate.getHours());
var minute = formatDigit(myDate.getMinutes());
var second = formatDigit(myDate.getSeconds());
return formats.replace(/Y|M|D|h|m|s/g, (matches) => {
return {
Y: year,
M: month,
D: day,
h: hour,
m: minute,
s: second
} [matches];
});
}
4.JS生成指定位数的随机整数
/**
* JS生成指定位数的随机整数
* @param count
* @returns {string}
*/
function getRandomNum(count){
var arr = new Array;
var reNum = "";
for(var i=0;i<count;i++){
arr[i] = parseInt(Math.random()*10);
reNum += String(arr[i]);
}
return reNum;
}
5.去除空格
/**
* JS生成指定位数的随机整数
* @param str
* @param type 1-所有空格 2-前后空格 3-前空格 4-后空格
* @returns {string}
*/
function strTrim(str, type) {
type = type || 2
switch (type) {
case 1:
return str.replace(/\s+/g, "");
case 2:
return str.replace(/(^\s*)|(\s*$)/g, "");
case 3:
return str.replace(/(^\s*)/g, "");
case 4:
return str.replace(/(\s*$)/g, "");
default:
return str;
}
}
6.JS格式化现在距${endTime}的剩余时间
/**
* JS格式化现在距${endTime}的剩余时间
* @param {Date} endTime
* @return {String}
*/
function formatRemainTime(endTime) {
var startDate = new Date(); //开始时间
var endDate = new Date(endTime); //结束时间
var t = endDate.getTime() - startDate.getTime(); //时间差
var d = 0,
h = 0,
m = 0,
s = 0;
if (t >= 0) {
d = Math.floor(t / 1000 / 3600 / 24);
h = Math.floor(t / 1000 / 60 / 60 % 24);
m = Math.floor(t / 1000 / 60 % 60);
s = Math.floor(t / 1000 % 60);
}
return d + "天 " + h + "小时 " + m + "分钟 " + s + "秒";
}
7.JS格式化${startTime}距现在的已过时间
/**
* JS格式化${startTime}距现在的已过时间
* @param {Date} startTime
* @return {String}
*/
function formatPassTime(startTime) {
var currentTime = Date.parse(new Date()),
time = currentTime - new Date(startTime),
day = parseInt(time / (1000 * 60 * 60 * 24)),
hour = parseInt(time / (1000 * 60 * 60)),
min = parseInt(time / (1000 * 60)),
month = parseInt(day / 30),
year = parseInt(month / 12);
if (year) return year + "年前";
if (month) return month + "个月前";
if (day) return day + "天前";
if (hour) return hour + "小时前";
if (min) return min + "分钟前";
else return '刚刚';
}
8.JS Base64字符串编码与解码
base64Encode("test"); // dGVzdA==
base64Decode(test); // test
/**
* BASE64加密
* @param str
* @returns {string}
*/
function base64Encode(str) {
return btoa(unescape(encodeURIComponent(str)));
}
/**
* BASE64解密
* @param str
* @returns {string}
*/
function base64Decode(str) {
return decodeURIComponent(escape(atob(str)));
}
9.JS检查输入的字符是否具有特殊字符
checkQuote("dasd1!/,/."); // true
checkQuote("52014sdsda"); // false
/**
* JS检查输入的字符是否具有特殊字符
* @param str 字符串
* @returns true 或 false; true表示包含特殊字符 主要用于注册信息的时候验证
*/
function checkQuote(str) {
var items = new Array("~", "`", "!", "@", "#", "$", "%", "^", "&", "*", "{", "}", "[", "]", "(", ")");
items.push(":", ";", "'", "|", "\", "<", ">", "?", "/", "<<", ">>", "||", "//");
items.push("select", "delete", "update", "insert", "create", "drop", "alter", "trancate");
str = str.toLowerCase();
for ( var i = 0; i < items.length; i++) {
if (str.indexOf(items[i]) >= 0) {
return true;
}
}
return false;
}
10.JS将手机号格式化,中间部分以 * 号代替
phoneToStar("16666666666"); // 166****6666
/**
* JS将手机号格式化,中间部分以 * 号代替
* @param phone
* @returns {string | * | void}
*/
function phoneToStar( phone ) {
return phone.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2");
}
11.JS获取地址栏参数的值
// 若当前的URL地址为:a.html?t1=1&t2=2&t3=3
console.log(getUrlParam("t1")); // 1
/**
* JS获取地址栏参数的值
* @param name 对应的参数
* @returns {*} 如果有,则返回参数值,没有则返回null
*/
function getUrlParam(name){
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg);
if (r != null) {
return unescape(r[2]);
} else {
return null;
}
}
12.JS时间个性化输出功能
//可用于列表展示的时间显示
console.log(timeFormat(new Date())); // 例:刚刚
/**
* JS时间个性化输出功能
* 1、< 60s, 显示为“刚刚”
* 2、>= 1min && < 60 min, 显示与当前时间差“XX分钟前”
* 3、>= 60min && < 1day, 显示与当前时间差“今天 XX:XX”
* 4、>= 1day && < 1year, 显示日期“XX月XX日 XX:XX”
* 5、>= 1year, 显示具体日期“XXXX年XX月XX日 XX:XX”
* @param time
* @returns {string}
*/
function timeFormat(time){
var date = new Date(time),
curDate = new Date(),
year = date.getFullYear(),
month = date.getMonth() + 10,
day = date.getDate(),
hour = date.getHours(),
minute = date.getMinutes(),
curYear = curDate.getFullYear(),
curHour = curDate.getHours(),
timeStr;
if(year < curYear){
timeStr = year +'年'+ month +'月'+ day +'日 '+ hour +':'+ minute;
}else{
var pastTime = curDate - date,
pastH = pastTime/3600000;
if(pastH > curHour){
timeStr = month +'月'+ day +'日 '+ hour +':'+ minute;
}else if(pastH >= 1){
timeStr = '今天 ' + hour +':'+ minute +'分';
}else{
var pastM = curDate.getMinutes() - minute;
if(pastM > 1){
timeStr = pastM +'分钟前';
}else{
timeStr = '刚刚';
}
}
}
return timeStr;
}
13.JS生成UUID
generateUUID(); // 例如:7ceb31a7-41b9-45ed-915b-14c7ad0fddf6
/**
* generateUUID 生成UUID
* @returns {string} 返回字符串
*/
function generateUUID(){
var d = new Date().getTime();
var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = (d + Math.random()*16)%16 | 0;
d = Math.floor(d/16);
return (c=='x' ? r : (r&0x7|0x8)).toString(16);
});
return uuid;
}
14.函数去抖
//调用
let n = 1;
function func () {
n += 1;
console.log('n', n);
}
window.onresize = debance(func, 1000);
function debance(fn, delay) {
let t = null;
return function() {
let that = this;
let args = arguments;
clearTimeout(t);
t = setTimeout(function() {
fn.apply(context, args);
}, delay);
}
}
15.函数节流
//调用
let n = 1;
function func () {
n += 1;
console.log('n', n);
}
window.onresize = throttle(func, 1000);
function throttle (fn, delay) {
let preTime = Date.now();
return function() {
let that = this;
let args = arguments;
let nowTime = Date.now();
if (preTime + delay < nowTime) {
fn.apply(that, args);
preTime = nowTime;
}
}
}
发表评论
还没有评论,快来抢沙发吧!