目录
「String Skill」:字符串技巧
「Number Skill」:数值技巧
「Boolean Skill」:布尔技巧
「Array Skill」:数组技巧
「Object Skill」:对象技巧
「Function Skill」:函数技巧
「DOM Skill」:DOM技巧
备注
代码只作演示用途,不会详细说明ES6语法
如有不明白的语法问题可以参考阮一峰老师的《ES6标准入门》
《ES6标准入门》一直保持更新,建议收藏,平时查看
String Skill 对比时间
时间个位数形式需补0
1 2 3 4 const time1 = "2019-02-14 21:00:00" ;const time2 = "2019-05-01 09:00:00" ;const overtime = time1 > time2;
格式化金钱 1 2 3 const ThousandNum = num => num.toString().replace(/\B(?=(\d{3})+(?!\d))/g , "," );const money = ThousandNum(20190214 );
生成随机ID 1 2 3 const RandomId = len => Math .random().toString(36 ).substr(3 , len);const id = RandomId(10 );
生成随机HEX色值 1 2 3 const RandomColor = () => "#" + Math .floor(Math .random() * 0xffffff ).toString(16 ).padEnd(6 , "0" );const color = RandomColor();
生成星级评分 1 2 3 const StartScore = rate => "★★★★★☆☆☆☆☆" .slice(5 - rate, 10 - rate);const start = StartScore(3 );
操作URL查询参数 1 2 3 const params = new URLSearchParams(location.search.replace(/\?/ig , "" )); params.has("young" ); params.get("sex" );
Number Skill 取整
代替正数的Math.floor()
,代替负数的Math.ceil()
1 2 3 4 const num1 = ~~ 1.69 ;const num2 = 1.69 | 0 ;const num3 = 1.69 >> 0 ;
补零 1 2 3 const FillZero = (num, len ) => num.toString().padStart(len, "0" );const num = FillZero(169 , 5 );
转数值
只对null、""、false、数值字符串
有效
1 2 3 4 5 const num1 = +null ;const num2 = +"" ;const num3 = +false ;const num4 = +"169" ;
时间戳 1 2 const timestamp = +new Date ("2019-02-14" );
精确小数 1 2 3 const RoundNum = (num, decimal ) => Math .round(num * 10 ** decimal) / 10 ** decimal;const num = RoundNum(1.69 , 1 );
判断奇偶 1 2 3 const OddEven = num => !!(num & 1 ) ? "odd" : "even" ;const num = OddEven(2 );
取最小最大值 1 2 3 4 const arr = [0 , 1 , 2 ];const min = Math .min(...arr);const max = Math .max(...arr);
生成范围随机数 1 2 const RandomNum = (min, max ) => Math .floor(Math .random() * (max - min + 1 )) + min;const num = RandomNum(1 , 10 );
Boolean Skill 短路运算符 1 2 3 const a = d && 1 ; const b = d || 1 ; const c = !d;
判断数据类型
可判断类型:undefined、null、string、number、boolean、array、object、symbol、date、regexp、function、asyncfunction、arguments、set、map、weakset、weakmap
1 2 3 4 5 6 7 8 9 function DataType (tgt, type ) { const dataType = Object .prototype.toString.call(tgt).replace(/\[object (\w+)\]/ , "$1" ).toLowerCase(); return type ? dataType === type : dataType; } DataType("young" ); DataType(20190214 ); DataType(true ); DataType([], "array" ); DataType({}, "array" );
是否为空数组 1 2 3 const arr = [];const flag = Array .isArray(arr) && !arr.length;
是否为空对象 1 2 3 const obj = {};const flag = DataType(obj, "object" ) && !Object .keys(obj).length;
满足条件时执行 1 2 3 4 5 6 const flagA = true ; const flagB = false ; (flagA || flagB) && Func(); (flagA || !flagB) && Func(); flagA && flagB && Func(); flagA && !flagB && Func();
为非假值时执行 1 2 const flag = false ; !flag && Func();
数组不为空时执行 1 2 const arr = [0 , 1 , 2 ];arr.length && Func();
对象不为空时执行 1 2 const obj = { a : 0 , b : 1 , c : 2 };Object .keys(obj).length && Func();
函数退出代替条件分支退出 1 2 3 4 5 6 7 8 if (flag) { Func(); return false ; } if (flag) { return Func(); }
switch/case使用区间 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 const age = 26 ;switch (true ) { case isNaN (age): console .log("not a number" ); break ; case (age < 18 ): console .log("under age" ); break ; case (age >= 18 ): console .log("adult" ); break ; default : console .log("please set your age" ); break ; }
Array Skill 克隆数组 1 2 3 const _arr = [0 , 1 , 2 ];const arr = [..._arr];
合并数组 1 2 3 4 const arr1 = [0 , 1 , 2 ];const arr2 = [3 , 4 , 5 ];const arr = [...arr1, ...arr2];
去重数组 1 2 const arr = [...new Set ([0 , 1 , 1 , null , null ])];
混淆数组 1 2 const arr = [0 , 1 , 2 , 3 , 4 , 5 ].slice().sort(() => Math .random() - .5 );
清空数组 1 2 3 const arr = [0 , 1 , 2 ];arr.length = 0 ;
截断数组 1 2 3 const arr = [0 , 1 , 2 ];arr.length = 2 ;
交换赋值 1 2 3 4 let a = 0 ;let b = 1 ;[a, b] = [b, a];
过滤空值
空值:undefined、null、””、0、false、NaN
1 2 const arr = [undefined , null , "" , 0 , false , NaN , 1 , 2 ].filter(Boolean );
异步累计 1 2 3 4 5 6 7 8 9 async function Func (deps ) { return deps.reduce(async (t, v) => { const dep = await t; const version = await Todo(v); dep[v] = version; return dep; }, Promise .resolve({})); } const result = await Func();
数组首部插入成员 1 2 3 4 5 let arr = [1 , 2 ]; arr.unshift(0 ); arr = [0 ].concat(arr); arr = [0 , ...arr];
数组尾部插入成员 1 2 3 4 5 6 let arr = [0 , 1 ]; arr.push(2 ); arr.concat(2 ); arr[arr.length] = 2 ; arr = [...arr, 2 ];
统计数组成员个数 1 2 3 4 5 6 const arr = [0 , 1 , 1 , 2 , 2 , 2 ];const count = arr.reduce((t, v ) => { t[v] = t[v] ? ++t[v] : 1 ; return t; }, {});
解构数组成员嵌套 1 2 3 const arr = [0 , 1 , [2 , 3 , [4 , 5 ]]];const [a, b, [c, d, [e, f]]] = arr;
解构数组成员别名 1 2 3 const arr = [0 , 1 , 2 ];const { 0 : a, 1 : b, 2 : c } = arr;
解构数组成员默认值 1 2 3 const arr = [0 , 1 , 2 ];const [a, b, c = 3 , d = 4 ] = arr;
获取随机数组成员 1 2 3 const arr = [0 , 1 , 2 , 3 , 4 , 5 ];const randomItem = arr[Math .floor(Math .random() * arr.length)];
创建指定长度数组 1 2 const arr = [...new Array (3 ).keys()];
创建指定长度且值相等的数组 1 2 const arr = new Array (3 ).fill(0 );
reduce代替map和filter 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 const _arr = [0 , 1 , 2 ];const arr = _arr.map(v => v * 2 );const arr = _arr.reduce((t, v ) => { t.push(v * 2 ); return t; }, []); const arr = _arr.filter(v => v > 0 );const arr = _arr.reduce((t, v ) => { v > 0 && t.push(v); return t; }, []); const arr = _arr.map(v => v * 2 ).filter(v => v > 2 );const arr = _arr.reduce((t, v ) => { v = v * 2 ; v > 2 && t.push(v); return t; }, []);
Object Skill 克隆对象 1 2 3 4 const _obj = { a: 0 , b: 1 , c: 2 }; // 以下方法任选一种 const obj = { ..._obj }; const obj = JSON.parse(JSON.stringify(_obj)); // obj => { a: 0 , b: 1 , c: 2 }
合并对象 1 2 3 4 const obj1 = { a : 0 , b : 1 , c : 2 };const obj2 = { c : 3 , d : 4 , e : 5 };const obj = { ...obj1, ...obj2 };
对象字面量
获取环境变量时必用此方法,用它一直爽,一直用它一直爽
1 2 3 4 5 6 7 const env = "prod" ;const link = { dev: "Development Address" , test: "Testing Address" , prod: "Production Address" }[env];
对象变量属性 1 2 3 4 5 6 7 const flag = false ;const obj = { a: 0 , b: 1 , [flag ? "c" : "d" ]: 2 };
创建纯空对象 1 2 3 const obj = Object .create(null );Object .prototype.a = 0 ;
删除对象无用属性 1 2 3 const obj = { a : 0 , b : 1 , c : 2 }; const { a, ...rest } = obj;
解构对象属性嵌套 1 2 3 const obj = { a : 0 , b : 1 , c : { d : 2 , e : 3 } };const { c : { d, e } } = obj;
解构对象属性别名 1 2 3 const obj = { a : 0 , b : 1 , c : 2 };const { a, b : d, c : e } = obj;
解构对象属性默认值 1 2 3 const obj = { a : 0 , b : 1 , c : 2 };const { a, b = 2 , d = 3 } = obj;
Function Skill 函数自执行 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 const Func = function ( ) {}(); (function ( ) {})(); (function ( ) {}()); [function ( ) {}()]; + function ( ) {}(); - function ( ) {}(); ~ function ( ) {}(); ! function ( ) {}(); new function ( ) {};new function ( ) {}();void function ( ) {}();typeof function ( ) {}();delete function ( ) {}();1 , function ( ) {}();1 ^ function ( ) {}();1 > function ( ) {}();
隐式返回值
只能用于单语句返回值箭头函数
,如果返回值是对象必须使用()
包住
1 2 3 4 5 const Func = function (name ) { return "I Love " + name; }; const Func = name => "I Love " + name;
一次性函数
适用于运行一些只需执行一次的初始化代码
1 2 3 4 5 6 function Func ( ) { console .log("x" ); Func = function ( ) { console .log("y" ); } }
惰性载入函数
函数内判断分支较多较复杂时可大大节约资源开销
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 function Func ( ) { if (a === b) { console .log("x" ); } else { console .log("y" ); } } function Func ( ) { if (a === b) { Func = function ( ) { console .log("x" ); } } else { Func = function ( ) { console .log("y" ); } } return Func(); }
检测非空参数 1 2 3 4 5 6 7 8 function IsRequired ( ) { throw new Error ("param is required" ); } function Func (name = IsRequired( )) { console .log("I Love " + name); } Func(); Func("You" );
字符串创建函数 1 const Func = new Function ("name" , "console.log(\"I Love \" + name)" );
优雅处理错误信息 1 2 3 4 5 try { Func(); } catch (e) { location.href = "https://stackoverflow.com/search?q=[js]+" + e.message; }
优雅处理Async/Await参数 1 2 3 4 function AsyncTo (promise ) { return promise.then(data => [null , data]).catch(err => [err]); } const [err, res] = await AsyncTo(Func());
优雅处理多个函数返回值 1 2 3 4 5 6 7 function Func ( ) { return Promise .all([ fetch("/user" ), fetch("/comment" ) ]); } const [user, comment] = await Func();
DOM Skill 显示全部DOM边框
调试页面元素边界时使用
1 2 3 [].forEach.call($$("*" ), dom => { dom.style.outline = "1px solid #" + (~~(Math .random() * (1 << 24 ))).toString(16 ); });
自适应页面
页面基于一张设计图但需做多款机型自适应,元素尺寸使用rem
进行设置
1 2 3 4 5 6 function AutoResponse (width = 750 ) { const target = document .documentElement; target.clientWidth >= 600 ? (target.style.fontSize = "80px" ) : (target.style.fontSize = target.clientWidth / width * 100 + "px" ); }
过滤XSS 1 2 3 4 5 6 7 function FilterXss (content ) { let elem = document .createElement("div" ); elem.innerText = content; const result = elem.innerHTML; elem = null ; return result; }
存取LocalStorage
反序列化取,序列化存
1 2 const love = JSON .parse(localStorage.getItem("love" ));localStorage.setItem("love" , JSON .stringify("I Love You" ));
总结 最后送大家一个键盘!
1 2 (_ => [..."`1234567890-=~~QWERTYUIOP[]\\~ASDFGHJKL;'~~ZXCVBNM,./~" ].map(x => (o+=`/${b='_' .repeat(w=x<y?2 :' 667699' [x=["Bs" ,"Tab" ,"Caps" ,"Enter" ][p++]||'Shift' ,p])} \\|` ,m+=y+(x+' ' ).slice(0 ,w)+y+y,n+=y+b+y+y,l+=' __' +b)[73 ]&&(k.push(l,m,n,o),l='' ,m=n=o=y),m=n=o=y='|' ,p=l=k=[])&&k.join` ` )()