今天是1024,祝大家节日快乐!
1.js实现sleep
const sleep = time => {
return new Promise(resolve => setTimeout(resolve,time)
) }
sleep(1000).then(()=>{ console.log(1) })
2.检测当前宿主环境
检测当前宿主环境是否是浏览器:通过判断 window
对象是否存在即可
export const inBrowser = typeof window !== 'undefined'
export const inWeex = typeof WXEnvironment !== 'undefined' && !!WXEnvironment.platform
export const weexPlatform = inWeex && WXEnvironment.platform.toLowerCase()
export const UA = inBrowser && window.navigator.userAgent.toLowerCase()
export const isIE = UA && /msie|trident/.test(UA)
export const isIE9 = UA && UA.indexOf('msie 9.0') > 0
export const isEdge = UA && UA.indexOf('edge/') > 0
export const isAndroid = (UA && UA.indexOf('android') > 0) || (weexPlatform === 'android')
export const isIOS = (UA && /iphone|ipad|ipod|ios/.test(UA)) || (weexPlatform === 'ios')
export const isChrome = UA && /chrome\/\d+/.test(UA) && !isEdge
export const isPhantomJS = UA && /phantomjs/.test(UA)
export const isFF = UA && UA.match(/firefox\/(\d+)/)
3.获取地址栏传递的参数值
/*
* getUrlParam(paraName)
* 功能:获取url地址栏中指定参数名对应的参数值
* 参数paraName:string:参数名.
* 返回:参数值.
*/
function getUrlParam(paraName) {
var url = document.location.toString().substring(0, document.location.toString().length)
var arrObj = url.split('?')
if (arrObj.length > 1) {
var arrPara = arrObj[1].split('&')
var arr
for (var i = 0; i < arrPara.length; i++) {
arr = arrPara[i].split('=')
if (arr !== null && arr[0] === paraName) {
return arr[1]
}
}
return ''
} else {
return ''
}
}
4.添加金额千位分隔符
/*
* formatMoney(s,type)
* 功能:金额按千位逗号分隔
* 参数:s,需要格式化的金额数值.
* 参数:type,判断格式化后的金额是否需要小数位.
* 返回:返回格式化后的数值字符串.
*/
function formatMoney(s, type) {
if (/[^0-9\.]/.test(s))
return "0.00";
if (s == null || s == "null" || s == "")
return "0.00";
s = s.toString().replace(/^(\d*)$/, "$1.");
s = (s + "00").replace(/(\d*\.\d\d)\d*/, "$1");
s = s.replace(".", ",");
var re = /(\d)(\d{3},)/;
while (re.test(s))
s = s.replace(re, "$1,$2");
s = s.replace(/,(\d\d)$/, ".$1");
if (type == 0) {
var a = s.split(".");
if (a[1] == "00") {
s = a[0];
}
}
return s;
}
5.cookie使用
encodeURIComponent 可以将存储的中文进行转换
function setCookie(key, value, iDay) {
// var oDate = new Date();
// oDate.setTime(oDate.getTime() + 5000);//超时时间2分钟
// console.log(oDate.toGMTString())
// document.cookie = "username=123";
document.cookie.expires = 0;
document.cookie.Path = '/';
document.cookie = key + '=' + encodeURIComponent(value) + ';Path=/';
// console.log(key + '=' + value + ';expires=' + 0+';Path=/')
};
function removeCookie(key) {
var _this = this;
setCookie(key, '', -1);//这里只需要把Cookie保质期退回一天便可以删除
};
function getCookie(key) {
var cookieArr = document.cookie.split('; ');
for (var i = 0; i < cookieArr.length; i++) {
var arr = cookieArr[i].split('=');
if (arr[0] === key) {
return decodeURIComponent(arr[1]);
}
}
return false;
}
6.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"}
7.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);
}
}
8.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) + '%')
}
})
}
9.禁止某些键盘事件
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)
});
10.禁止右键、选择、复制
['contextmenu', 'selectstart', 'copy'].forEach(function(ev){
document.addEventListener(ev, function(event){
return event.returnValue = false
})
});
11.dateFormater:格式化时间
function dateFormater(formater, t){
let date = t ? new Date(t) : new Date(),
Y = date.getFullYear() + '',
M = date.getMonth() + 1,
D = date.getDate(),
H = date.getHours(),
m = date.getMinutes(),
s = date.getSeconds();
return formater.replace(/YYYY|yyyy/g,Y)
.replace(/YY|yy/g,Y.substr(2,2))
.replace(/MM/g,(M<10?'0':'') + M)
.replace(/DD/g,(D<10?'0':'') + D)
.replace(/HH|hh/g,(H<10?'0':'') + H)
.replace(/mm/g,(m<10?'0':'') + m)
.replace(/ss/g,(s<10?'0':'') + s)
}
// dateFormater('YYYY-MM-DD HH:mm', t) ==> 2019-06-26 18:30
// dateFormater('YYYYMMDDHHmm', t) ==> 201906261830
12.dateStrForma:将指定字符串由一种时间格式转化为另一种
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
13.isStatic:检测数据是不是除了symbol外的原始数据
function isStatic(value) {
return(
typeof value === 'string' ||
typeof value === 'number' ||
typeof value === 'boolean' ||
typeof value === 'undefined' ||
value === null
)
}
14.isPrimitive:检测数据是不是原始数据
function isPrimitive(value) {
return isStatic(value) || typeof value === 'symbol'
}
15.isObject:判断数据是不是引用类型的数据 (例如: arrays, functions, objects, regexes, new Number(0),以及 new String(’’))
function isObject(value) {
let type = typeof value;
return value != null && (type == 'object' || type == 'function');
}
16.isObjectLike:检查 value 是否是 类对象。 如果一个值是类对象,那么它不应该是 null,而且 typeof 后的结果是 "object"
function isObjectLike(value) {
return value != null && typeof value == 'object';
}
17.getRawType:获取数据类型,返回结果为 Number、String、Object、Array等
function getRawType(value) {
return Object.prototype.toString.call(value).slice(8, -1)
}
//getoRawType([]) ==> Array
18.isPlainObject:判断数据是不是Object类型的数据
function isPlainObject(obj) {
return Object.prototype.toString.call(obj) === '[object Object]'
}
19.isLength:检查 value 是否为有效的类数组长度
function isLength(value) {
return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= Number.MAX_SAFE_INTEGER;
}
20.isArrayLike:检查 value 是否是类数组
function isArrayLike(value) {
return value != null && isLength(value.length) && !isFunction(value);
}
21.isEmpty:检查 value 是否为空
function isEmpty(value) {
if (value == null) {
return true;
}
if (isArrayLike(value)) {
return !value.length;
}else if(isPlainObject(value)){
for (let key in value) {
if (hasOwnProperty.call(value, key)) {
return false;
}
}
}
return false;
}
22.cached:记忆函数:缓存函数的运算结果
function cached(fn) {
let cache = Object.create(null);
return function cachedFn(str) {
let hit = cache[str];
return hit || (cache[str] = fn(str))
}
}
23.camelize:横线转驼峰命名
let camelizeRE = /-(\w)/g;
function camelize(str) {
return str.replace(camelizeRE, function(_, c) {
return c ? c.toUpperCase() : '';
})
}
//ab-cd-ef ==> abCdEf
//使用记忆函数
let _camelize = cached(camelize)
24.hyphenate:驼峰命名转横线命名:拆分字符串,使用 - 相连,并且转换为小写
let hyphenateRE = /\B([A-Z])/g;
function hyphenate(str){
return str.replace(hyphenateRE, '-$1').toLowerCase()
}
//abCd ==> ab-cd
//使用记忆函数
let _hyphenate = cached(hyphenate);
25.capitalize:字符串首位大写
function capitalize(str){
return str.charAt(0).toUpperCase() + str.slice(1)
}
// abc ==> Abc
//使用记忆函数
let _capitalize = cached(capitalize)
26.extend:将属性混合到目标对象中
function extend(to, _from) {
for(let key in _from) {
to[key] = _from[key];
}
return to
}
27.getExplorerInfo:获取浏览器信息
function getExplorerInfo() {
let t = navigator.userAgent.toLowerCase();
return 0 <= t.indexOf("msie") ? { //ie < 11
type: "IE",
version: Number(t.match(/msie ([\d]+)/)[1])
} : !!t.match(/trident\/.+?rv:(([\d.]+))/) ? { // ie 11
type: "IE",
version: 11
} : 0 <= t.indexOf("edge") ? {
type: "Edge",
version: Number(t.match(/edge\/([\d]+)/)[1])
} : 0 <= t.indexOf("firefox") ? {
type: "Firefox",
version: Number(t.match(/firefox\/([\d]+)/)[1])
} : 0 <= t.indexOf("chrome") ? {
type: "Chrome",
version: Number(t.match(/chrome\/([\d]+)/)[1])
} : 0 <= t.indexOf("opera") ? {
type: "Opera",
version: Number(t.match(/opera.([\d]+)/)[1])
} : 0 <= t.indexOf("Safari") ? {
type: "Safari",
version: Number(t.match(/version\/([\d]+)/)[1])
} : {
type: t,
version: -1
}
}
28.isPCBroswer:检测是否为PC端浏览器模式
function isPCBroswer() {
let e = navigator.userAgent.toLowerCase()
, t = "ipad" == e.match(/ipad/i)
, i = "iphone" == e.match(/iphone/i)
, r = "midp" == e.match(/midp/i)
, n = "rv:1.2.3.4" == e.match(/rv:1.2.3.4/i)
, a = "ucweb" == e.match(/ucweb/i)
, o = "android" == e.match(/android/i)
, s = "windows ce" == e.match(/windows ce/i)
, l = "windows mobile" == e.match(/windows mobile/i);
return !(t || i || r || n || a || o || s || l)
}
29.unique:数组去重,返回一个新数组
function unique(arr){
if(!isArrayLink(arr)){ //不是类数组对象
return arr
}
let result = []
let objarr = []
let obj = Object.create(null)
arr.forEach(item => {
if(isStatic(item)){//是除了symbol外的原始数据
let key = item + '_' + getRawType(item);
if(!obj[key]){
obj[key] = true
result.push(item)
}
}else{//引用类型及symbol
if(!objarr.includes(item)){
objarr.push(item)
result.push(item)
}
}
})
return resulte
}
30.repeat:生成一个重复的字符串,有n个str组成,可修改为填充为数组等
function repeat(str, n) {
let res = '';
while(n) {
if(n % 2 === 1) {
res += str;
}
if(n > 1) {
str += str;
}
n >>= 1;
}
return res
};
//repeat('123',3) ==> 123123123
31.toFullScreen:全屏
function toFullScreen(){
let elem = document.body;
elem.webkitRequestFullScreen
? elem.webkitRequestFullScreen()
: elem.mozRequestFullScreen
? elem.mozRequestFullScreen()
: elem.msRequestFullscreen
? elem.msRequestFullscreen()
: elem.requestFullScreen
? elem.requestFullScreen()
: alert("浏览器不支持全屏");
}
32.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退出");
}
33.random:返回一个lower - upper之间的随机数
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
34.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
}
35.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
}