记录一些js的小技巧。
一些js小技巧 操作URL查询参数 const params = new URLSearchParams(location.search); params.has('key' ); params.get('value' );
取整
代替正数的 Math.floor(),代替负数的 Math.ceil()
const num1 = ~~2.3 ;const num2 = 2.3 | 0 ;const num3 = 2.3 >> 0 ;
短路运算 const a = d && 1 ; const b = d || 1 ; const c = !d;
判断空对象 const obj = {};const flag = !Object .keys(obj).length;
满足条件时执行 const flagA = true ; const flagB = false ; (flagA || flagB) && Func(); (flagA || !flagB) && Func(); flagA && flagB && Func(); flagA && !flagB && Func();
克隆数组 const arr = [1 , 2 , 3 ];const _arr = [...arr];
合并数组 const arr1 = [1 , 2 , 3 ];const arr2 = [4 , 5 , 6 ];const arr = [...arr1, ...arr2];
数组去重 const arr = [...new Set ([1 , 2 , 1 , 4 , 6 , null , null ])];
过滤空值 const arr = [undefined , null , "" , 0 , false , NaN , 1 , 2 ].filter(Boolean );
统计成员个数 const arr = [0 , 1 , 1 , 2 , 2 , 2 ];const count = arr.reduce((t, v ) => { t[v] = t[v] ? ++t[v] : 1 ; return t; }, {});
按属性对Object分类 const people = [ { name : 'Alice' , age : 20 }, { name : 'Max' , age : 21 }, { name : 'Tom' , age : 20 } ] const groupBy = (objectArr, property ) => { return objectArr.reduce((acc, obj ) => { const key = obj[property]; if (!acc[key]) { acc[key] = [] } acc[key].push(obj); return acc; }, {}) } const groupedPeople = groupBy(people, 'age' );
删除对象无用属性 const obj = { a : 0 , b : 1 , c : 2 }; const { a, ...rest } = obj;