29、dateStrForma:将指定字符串由一种时间格式转化为另一种
from的格式应对应str的位置
function dateStrForma(str, from, to){
//'20190626' 'YYYYMMDD' 'YYYY年MM月DD日'
str += ''
let Y = ''
if(~(Y = from.indexOf('YYYY'))){
Y = str.substr(Y, 4)
to = to.replace(/YYYY|yyyy/g,Y)
}else if(~(Y = from.indexOf('YY'))){
Y = str.substr(Y, 2)
to = to.replace(/YY|yy/g,Y)
}
let k,i
['M','D','H','h','m','s'].forEach(s =>{
i = from.indexOf(s+s)
k = ~i ? str.substr(i, 2) : ''
to = to.replace(s+s, k)
})
return to
}
// dateStrForma('20190626', 'YYYYMMDD', 'YYYY年MM月DD日') ==> 2019年06月26日
// dateStrForma('121220190626', '----YYYYMMDD', 'YYYY年MM月DD日') ==> 2019年06月26日
// dateStrForma('2019年06月26日', 'YYYY年MM月DD日', 'YYYYMMDD') ==> 20190626
// 一般的也可以使用正则来实现
//'2019年06月26日'.replace(/(\d{4})年(\d{2})月(\d{2})日/, '$1-$2-$3') ==> 2019-06-26
30、getPropByPath:根据字符串路径获取对象属性 : 'obj[0].count'
function getPropByPath(obj, path, strict) {
let tempObj = obj;
path = path.replace(/\[(\w+)\]/g, '.$1'); //将[0]转化为.0
path = path.replace(/^\./, ''); //去除开头的.
let keyArr = path.split('.'); //根据.切割
let i = 0;
for (let len = keyArr.length; i < len - 1; ++i) {
if (!tempObj && !strict) break;
let key = keyArr;
if (key in tempObj) {
tempObj = tempObj[key];
} else {
if (strict) {//开启严格模式,没找到对应key值,抛出错误
throw new Error('please transfer a valid prop path to form item!');
}
break;
}
}
return {
o: tempObj, //原始数据
k: keyArr, //key值
v: tempObj ? tempObj[keyArr] : null // key值对应的值
};
};
31、GetUrlParam:获取Url参数,返回一个对象
function GetUrlParam(){
let url = document.location.toString();
let arrObj = url.split("?");
let params = Object.create(null)
if (arrObj.length > 1){
arrObj = arrObj[1].split("&");
arrObj.forEach(item=>{
item = item.split("=");
params[item[0]] = item[1]
})
}
return params;
}
// ?a=1&b=2&c=3 ==> {a: "1", b: "2", c: "3"}
32、downloadFile:base64数据导出文件,文件下载
function downloadFile(filename, data){
let DownloadLink = document.createElement('a');
if ( DownloadLink ){
document.body.appendChild(DownloadLink);
DownloadLink.style = 'display: none';
DownloadLink.download = filename;
DownloadLink.href = data;
if ( document.createEvent ){
let DownloadEvt = document.createEvent('MouseEvents');
DownloadEvt.initEvent('click', true, false);
DownloadLink.dispatchEvent(DownloadEvt);
}
else if ( document.createEventObject )
DownloadLink.fireEvent('onclick');
else if (typeof DownloadLink.onclick == 'function' )
DownloadLink.onclick();
document.body.removeChild(DownloadLink);
}
}
33、toFullScreen:全屏
function toFullScreen(){
let elem = document.body;
elem.webkitRequestFullScreen
? elem.webkitRequestFullScreen()
: elem.mozRequestFullScreen
? elem.mozRequestFullScreen()
: elem.msRequestFullscreen
? elem.msRequestFullscreen()
: elem.requestFullScreen
? elem.requestFullScreen()
: alert("浏览器不支持全屏");
}
34、exitFullscreen:退出全屏
function exitFullscreen(){
let elem = parent.document;
elem.webkitCancelFullScreen
? elem.webkitCancelFullScreen()
: elem.mozCancelFullScreen
? elem.mozCancelFullScreen()
: elem.cancelFullScreen
? elem.cancelFullScreen()
: elem.msExitFullscreen
? elem.msExitFullscreen()
: elem.exitFullscreen
? elem.exitFullscreen()
: alert("切换失败,可尝试Esc退出");
}
35、requestAnimationFrame:window动画
window.requestAnimationFrame = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame ||
function (callback) {
//为了使setTimteout的尽可能的接近每秒60帧的效果
window.setTimeout(callback, 1000 / 60);
};
window.cancelAnimationFrame = window.cancelAnimationFrame ||
Window.webkitCancelAnimationFrame ||
window.mozCancelAnimationFrame ||
window.msCancelAnimationFrame ||
window.oCancelAnimationFrame ||
function (id) {
//为了使setTimteout的尽可能的接近每秒60帧的效果
window.clearTimeout(id);
}
36、_isNaN:检查数据是否是非数字值
原生的isNaN会把参数转换成数字(valueof),而null、true、false以及长度小于等于1的数组(元素为非NaN数据)会被转换成数字,这不是我想要的。Symbol类型的数据不具有valueof接口,所以isNaN会抛出错误,这里放在后面,可避免错误
function _isNaN(v){
return !(typeof v === 'string' || typeof v === 'number') || isNaN(v)
}
37、max:求取数组中非NaN数据中的最大值
function max(arr){
arr = arr.filter(item => !_isNaN(item))
return arr.length ? Math.max.apply(null, arr) : undefined
}
//max([1, 2, '11', null, 'fdf', []]) ==> 11
38、min:求取数组中非NaN数据中的最小值
function min(arr){
arr = arr.filter(item => !_isNaN(item))
return arr.length ? Math.min.apply(null, arr) : undefined
}
//min([1, 2, '11', null, 'fdf', []]) ==> 1
39、random:返回一个lower - upper之间的随机数
lower、upper无论正负与大小,但必须是非NaN的数据
function random(lower, upper){
lower = +lower || 0
upper = +upper || 0
return Math.random() * (upper - lower) + lower;
}
//random(0, 0.5) ==> 0.3567039135734613
//random(2, 1) ===> 1.6718418553475423
//random(-2, -1) ==> -1.4474325452361945
40、Object.keys:返回一个由一个给定对象的自身可枚举属性组成的数组
Object.keys = Object.keys || function keys(object) {
if(object === null || object === undefined){
throw new TypeError('Cannot convert undefined or null to object');
}
let result = []
if(isArrayLike(object) || isPlainObject(object)){
for (let key in object) {
object.hasOwnProperty(key) && ( result.push(key) )
}
}
return result
}
41、Object.values:返回一个给定对象自身的所有可枚举属性值的数组
Object.values = Object.values || function values(object) {
if(object === null || object === undefined){
throw new TypeError('Cannot convert undefined or null to object');
}
let result = []
if(isArrayLike(object) || isPlainObject(object)){
for (let key in object) {
object.hasOwnProperty(key) && ( result.push(object[key]) )
}
}
return result
}
42、arr.fill:使用 value 值来填充 array,从start位置开始, 到end位置结束(但不包含end位置),返回原数组
Array.prototype.fill = Array.prototype.fill || function fill(value, start, end) {
let ctx = this
let length = ctx.length;
start = parseInt(start)
if(isNaN(start)){
start = 0
}else if (start < 0) {
start = -start > length ? 0 : (length + start);
}
end = parseInt(end)
if(isNaN(end) || end > length){
end = length
}else if (end < 0) {
end += length;
}
while (start < end) {
ctx[start++] = value;
}
return ctx;
}
//Array(3).fill(2) ===> [2, 2, 2]
43、arr.includes:用来判断一个数组是否包含一个指定的值,如果是返回 true,否则false,可指定开始查询的位置
Array.prototype.includes = Array.prototype.includes || function includes(value, start){
let ctx = this
let length = ctx.length;
start = parseInt(start)
if(isNaN(start)){
start = 0
}else if (start < 0) {
start = -start > length ? 0 : (length + start);
}
let index = ctx.indexOf(value)
return index >= start;
}
44、arr.find:返回数组中通过测试(函数fn内判断)的第一个元素的值
Array.prototype.find = Array.prototype.find || function find(fn, ctx){
ctx = ctx || this
let result;
ctx.some((value, index, arr), thisValue) => {
return fn(value, index, arr) ? (result = value, true) : false
})
return result
}
45、arr.findIndex :返回数组中通过测试(函数fn内判断)的第一个元素的下标
Array.prototype.findIndex = Array.prototype.findIndex || function findIndex(fn, ctx){
ctx = ctx || this
let result;
ctx.some((value, index, arr), thisValue) => {
return fn(value, index, arr) ? (result = index, true) : false
})
return result
}
46、performance.timing:利用performance.timing进行性能分析
window.onload = function(){
setTimeout(function(){
let t = performance.timing
console.log('DNS查询耗时 :' + (t.domainLookupEnd - t.domainLookupStart).toFixed(0))
console.log('TCP链接耗时 :' + (t.connectEnd - t.connectStart).toFixed(0))
console.log('request请求耗时 :' + (t.responseEnd - t.responseStart).toFixed(0))
console.log('解析dom树耗时 :' + (t.domComplete - t.domInteractive).toFixed(0))
console.log('白屏时间 :' + (t.responseStart - t.navigationStart).toFixed(0))
console.log('domready时间 :' + (t.domContentLoadedEventEnd - t.navigationStart).toFixed(0))
console.log('onload时间 :' + (t.loadEventEnd - t.navigationStart).toFixed(0))
if(t = performance.memory){
console.log('js内存使用占比 :' + (t.usedJSHeapSize / t.totalJSHeapSize * 100).toFixed(2) + '%')
}
})
}
47、禁止某些键盘事件
document.addEventListener('keydown', function(event){
return !(
112 == event.keyCode || //F1
123 == event.keyCode || //F12
event.ctrlKey && 82 == event.keyCode || //ctrl + R
event.ctrlKey && 78 == event.keyCode || //ctrl + N
event.shiftKey && 121 == event.keyCode || //shift + F10
event.altKey && 115 == event.keyCode || //alt + F4
"A" == event.srcElement.tagName && event.shiftKey //shift + 点击a标签
) || (event.returnValue = false)
});
48、禁止右键、选择、复制
['contextmenu', 'selectstart', 'copy'].forEach(function(ev){
document.addEventListener(ev, function(event){
return event.returnValue = false
})
});
|
|