浏览器端加解密
//加密
function encode (str) {
return btoa(encodeURIComponent(str));
}
//解密
function decode (str) {
return decodeURIComponent(atob(str));
}
文字下划线转驼峰
function transfor(str) {
return str.replace(/(?<=[^_]+)_([a-z]|[A-Z])/g, (m, $1) => {
return $1.toUpperCase();
});
}
判断数据类型
function type (obj) {
return Object.prototype.toString.call(obj).replace(/\[object\s|\]/g,'');
}
console.log(type([])) //"Array"
console.log(type(1)) //"Number"
获取url上的参数
//返回一个{}
function getUrlParam(){
const param = {};
location.search.replace(/([^&=?]+)=([^&]+)/g,(m,$1,$2)=> param[$1] = $2);
return param;
}
数组去重(支持多维)
function uniqueArr(arr) {
return [...new Set(arr.flat(Infinity))]
}
页面回到顶部
window.scroll(0,0);//ie不支持
ocument.documentElement.scrollTop = 0;
#top//锚点
typeof
typeof 是操作符,不是函数。
可以添加括号,但是括号的作用是进行分组而非函数的调用
生成n个长度数组并迭代
Array.from(new Array(12),(x,i)=>i+1+'月')
数组快速乱序
Array.prototype.rad=function(){return this.sort((a,b)=>(Math.random()-0.5))}
页面元素添加1px边框(颜色随机)
//简写
[].forEach.call($$("*"),function(a){ a.style.outline="1px solid #"+(~~(Math.random()*(1<<24))).toString(16) })
//标准写法
[].forEach.call(
document.querySelectorAll('*'),
function(a){
a.style.outline="1px solid #" +
(parseInt(Math.random()*(1<<24)).toString(16))
}
)
常用正则汇总(待补充)
1和0互换
- 判断运算符
function turn(x){return !x && 1 || 0 } - 位运算
function turn(x){return ~x + 2}