日常业务实现时,有许多常用的,实用的JavaScript代码,梳理如下:
var IsEven = num => num % 2 === 0 (是否能整除2)
console.log(isEven(4)) //true
console.log(isEven(5)) // false
var randomBool = () => Math.random() < 0.5;
console.log(randomBool()) //得到随机的true或者false
var reverseStr = str => str.split('').reverse().join('');
reverseStr('i am skime') //反转后结果'emiks ma i'
var newFloat = (floatNum , n) => ~~(Math.pow(10, n) * floatNum) / Math.pow(10, n) ; //floatNum为需处理的数字, n为需要保留几位的位数
newFloat(13.1234567, 1); //13.1
newFloat(13.1234567, 2); //13.12
newFloat(13.1234567, 3); //13.123
newFloat(13.1234567, 4); //13.1234
let toTop = () => window.scrollTo({
top: 0 , behavior: 'smooth'})
toTop() //页面滚动至顶部
/**
* 格式化数字,如果数字小于10,则在前边补0
* @param {String/Number} _num 要判断的数字
* @return {String} 返回格式化后的数字
*/
formatTime: function(_num) {
var num = Number(_num);
if (num < 10) {
return '0' + num;
} else {
return num;
}
},
/**
* 把数字转为周数,比如1转为周一
* @param {Number} 要转换的数字
* @return {String} 转换后的结果
*/
weekFormat: function (_num) {
var weekList = ['日', '一', '二', '三', '四', '五', '六'];
var num = Number(_num);
return '周' + weekList[num];
},
/**
* 判断指定时间和当前时间是否在指定时间长度之外
* @param {String/Number} _timestamp 要比较的时间戳 秒级
* @param {Number} _len 时间长度 小时
* @return {Boolean} true为时间差大于指定时间长度,false则相反
*/
compareTime: function (_timestamp, _len) {
var now = new Date().getTime() / 1000;
var minus = Number(_timestamp) - parseInt(now);
var len = _len * 60 * 60;
if (minus > len) {
return true;
} else {
return false;
}
},
//传入dom节点判断该节点元素是否含有该类名,进行删除或添加操作
elemAddClassName:function(elem,className){
if(!elem.classList.contains(className)){
elem.classList.add(className);
}
},
elemRemoveClassName:function(elem,className){
if(elem.classList.contains(className)){
elem.classList.remove(className);
}
},
var trim = str => return str.replace(/(^\s*)|(\s*$)/g, "");
getTimeDiff(begin_date,end_date){
let startTime = begin_date;
let endTime = end_date;
let timeDiff = endTime - startTime;
if(timeDiff <= 0){
return diffArr = {
day : 0,
hour : 0,
min : 0,
sec : 0
}
}else{
let diffDay = parseInt(timeDiff/86400000) ;
let remain = timeDiff % 86400000 ;
let diffHour = parseInt(remain/3600000) ;
remain = remain % 3600000 ;
let diffmin = parseInt(remain/60000) ;
remain = remain % 60000 ;
let diffsec = parseInt(remain/1000);
return diffArr = {
day : diffDay,
hour : diffHour,
min : diffmin,
sec : diffsec
}
}
}